How to call validate method of Element-UI form

Johna picture Johna · Aug 30, 2018 · Viewed 17.3k times · Source

I'm trying design some forms with Element-UI in one of my Vue.js projects. I want to check if the form is valid before continuing any further action once the submit button is clicked.

Can anybody direct me to an example how to reference the element inside a Vue component and check its validity.

Following is my form setup.

 <div id="frmEventCreate">
 <el-form v-bind:model="data" v-bind:rules="rules">
    <el-form-item label="Event name" prop="name" required>
       <el-input v-model="data.name"></el-input>
    </el-form-item>

    <el-button type="success" v-on:click="next" icon="el-icon-arrow-right"> Next Step </el-button>
 </el-form>
 </div>

var objEvent = {neme: "Some Name"};
vmEventCreate = new Vue({
    el: '#frmEventCreate',
    data: {
        data: objEvent,
        rules: {
            name: [
                {required: true, message: 'Please input event name', trigger: 'blur'},
                {min: 10, max: 100, message: 'Length should be 10 to 100', trigger: 'blur'}
            ]
        },
    },
    methods: {
        next: function () {
            // need to check if the form is valid, here..
        }
    }
});

Answer

Allkin picture Allkin · Aug 30, 2018

Here is the link to the validation example in Element UI docs

You need to add a ref attribute to your form like this:

 <el-form v-bind:model="data" v-bind:rules="rules" ref="someForm">

Then, when you click on the submit button which is calling the next method in your case you can validate your form like this:

this.$refs['someForm'].validate((valid) => {
  if (valid) {
    alert('submit!');
  } else {
    console.log('error submit!!');
    return false;
  }
});