Project scenario:

Common forms will be filled in, such as new information, modify information, etc., as shown in the following figure

I believe everyone is very familiar with the above verification, not much beep beep This article mainly wants to write the verification rule custom related content


Verify valid mobile phone number (example)

Implement as shown below:


Implementation steps:

step 1

Ready reg expression, baidu can be phone number -- /^((()13[0-9] {1}) | (15[0-9] {1}) | (18[0-9] {1}))+\d{8$/})Copy the code

step 2

The phone_number field name for prop validation and the phone_number field name for V-model binding should also be the same<el-form :model="ruleForm" ref="ruleForm" :rules="rules">
  <el-form-item label="XXX Phone Number" prop="phone_number">
    <el-input v-model="ruleForm.phone_number"></el-input>
  </el-form-item>
 </el-form>
 
<el-button type="primary" @click="submitForm('ruleForm')">Immediately create</el-button>
Copy the code

step 3

 data(){hungry me documentation says define a checkPhon_unm callback here// Verify the phone number
    var checkPhon_unm = (rule, value, callback) = > {
      if (value) {
        if (!/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(value)) {
          callback(new Error("Please enter the correct phone number!"));
        } else{ callback(); }}else{ callback(); }};return {
     rules: {
        phone_number: [{ validator: checkPhon_unm, trigger: "blur"}],}}; },methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) = > {
          if (valid) {
            alert('submit! ');
          } else {
            console.log('error submit!! ');
            return false; }}); },Copy the code

Conclusion:

  • That’s the phone number. Everything else is the same
  • Specific business analysis, some non-mandatory regular verification, some reverse
  • If the form field needs a custom layout and you don’t want to use the local effects that come with me, it’s best to put the el-Form package in the outermost layer, otherwise you might not be able to trigger the validation callback