Skip to content
Advertisement

How do I validate with number and regex in vue js?

I have to validate textbox accepting only numeric value and number must start with 7 or 8 or 9 (regex).

I have already done maxlength, minlength and required rule. Which are perfectly working fine. But I don’t know how to validate with only accepts number and regex. I have tried some of the syntaxes but not working.

<tab-content title="RELATIONSHIP DETAILS" icon="ti-info-alt" :before-change="validateFirstStep">
<el-form :inline="true" :model="formInline1" class="demo-form-inline" :rules="rules1" ref="ruleForm1">
<el-form-item label="Mobile Number" prop="mobno">
          <el-input maxlength="10" v-model="formInline1.mobno" placeholder="Mobile Number"></el-input>
        </el-form-item>

</el-form>

    </tab-content>

<script>
const app= new Vue({
   el: '#app',
     data() {
       return {
         formInline1: {
mobno:'',
},
         rules1: {
 mobno: [{
             required: true,
             message: 'Please enter Mobile Number',
             trigger: 'blur'
           }, {
             min: 10,
             max: 10,
             message: 'Length must be 10',
             trigger: 'blur'
           }],
}
       },
       methods: {
         onComplete: function() {
           alert('Yay. Done!');
         },
validateFirstStep() {
           return new Promise((resolve, reject) => {
             this.$refs.ruleForm1.validate((valid) => {
               resolve(valid);
             });
           })
         },
}
  })
</script>

Advertisement

Answer

The validation rule would be something like this:

{
  trigger: 'blur',
  validator (rule, value, callback) {
    if (/^[789]d{9}$/.test(value)) {
      callback();
    } else {
      callback(new Error('Mobile number must be 10 digits starting 7, 8 or 9'));
    }
  }
}

Calling the callback with no argument indicates a success, calling it with an error indicates a validation failure.

The RegExp checks for 7, 8 or 9 followed by 9 other digits. It isn’t strictly necessary to be that precise as there’s already a validation rule that checks for 10 characters in total. e.g. /^[789]d*$/ would also work given we know there are 10 characters.

In practice it might be better to split this into two separate pieces, one that confirms all the digits are numbers and another that checks the first digit is 7, 8 or 9. That would allow for different error messages to be shown for the two cases.

Here’s a complete example:

const app = new Vue({
  el: '#app',

  data () {
    return {
      formInline1: {
        mobno: '',
      },
      rules1: {
        mobno: [{
          required: true,
          message: 'Please enter Mobile Number',
          trigger: 'blur'
        }, {
          min: 10,
          max: 10,
          message: 'Length must be 10',
          trigger: 'blur'
        }, {
          trigger: 'blur',
          validator (rule, value, callback) {
            if (/^[789]d{9}$/.test(value)) {
              callback();
            } else {
              callback(new Error('Mobile number must be 10 digits starting 7, 8 or 9'));
            }
          }
        }]
      }
    }
  }
});
<link rel="stylesheet" href="https://unpkg.com/element-ui@2.10.1/lib/theme-chalk/index.css">
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui@2.10.1/lib/index.js"></script>
<div id="app">
  <el-form :inline="true" :model="formInline1" :rules="rules1">
    <el-form-item label="Mobile Number" prop="mobno">
      <el-input maxlength="10" v-model="formInline1.mobno" placeholder="Mobile Number"></el-input>
    </el-form-item>
  </el-form>
</div>

Update:

An example of separate messages for the two cases:

if (/D/.test(value)) {
  callback(new Error('Must all be numbers'));
} else if (!/^[789]/.test(value)) {
  callback(new Error('Must start 7, 8 or 9'));
} else {
  callback();
}

You could take it even further and partition them into two separate validators but that would likely only be useful if you needed to reuse one of them independently of the other.

Further update:

It seems that Element uses async-validator for validation so we can use a pattern instead of a custom validator:

const app = new Vue({
  el: '#app',

  data () {
    return {
      formInline1: {
        mobno: '',
      },
      rules1: {
        mobno: [{
          required: true,
          message: 'Please enter Mobile Number',
          trigger: 'blur'
        }, {
          min: 10,
          max: 10,
          message: 'Length must be 10',
          trigger: 'blur'
        }, {
          pattern: /^d*$/,
          message: 'Must be all numbers',
          trigger: 'blur'
        }, {
          pattern: /^[789]/,
          message: 'Must start 7, 8 or 9',
          trigger: 'blur'
        }]
      }
    }
  }
});
<link rel="stylesheet" href="https://unpkg.com/element-ui@2.10.1/lib/theme-chalk/index.css">
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui@2.10.1/lib/index.js"></script>
<div id="app">
  <el-form :inline="true" :model="formInline1" :rules="rules1">
    <el-form-item label="Mobile Number" prop="mobno">
      <el-input maxlength="10" v-model="formInline1.mobno" placeholder="Mobile Number"></el-input>
    </el-form-item>
  </el-form>
</div>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement