SoFunction
Updated on 2025-04-07

Detailed explanation of vant2 Automatic check form verification -validate

Below is a description of vant2 automatic check form verification -validate

ref to

<van-form @submit="onSubmit" ref="form"> tag ;

// Check whether the mobile phone number is qualified      await this.$("mobile");

The rules object defined in data;

rules: {
        mobile: [
          // Required          { required: true, message: "Please fill in the username" },
          // 1 3-9 Starting at home 9 0-9 numbers          { pattern: /^1[3-9]\d{9}$/, message: "The mobile phone number is incorrect" },
        ],
        code: [
          { required: true, message: "Please fill in your password" },
          { pattern: /\d{6}$/, message: "Verification code error" },
        ],
      },

Rules of use:

&lt;van-field
        v-model=""
        name="mobile"
        icon-prefix="zlx"
        left-icon="shouji"
        maxlength="11"
        placeholder="Please enter your mobile phone number"
        :rules=""
      /&gt;

vant2 form component Field checks error on iOS

Problem description

The user's input needs to be checked. If the length exceeds the error message, the regular expression is used for verification. The code is as follows.

&lt;van-field v-model="location" name="location" label="Place" placeholder="Please enter the business trip location" :rules="[{ required: true, pattern: /^\S{1,7}$/g, message: 'Please enter 7 characters within 7' }]" /&gt;

It can be checked normally on Android phones, but the iOS system will prompt an error no matter how many characters are entered. The reason may be that the iOS input method will enter special characters

Solution

Listen to input, remove special characters and then make judgments (real-time verification)

watch: {
    location(val) {
      if ((/\s/g, '').length &gt; 7) {
      	// Add error handling      	// ....
        ('Length exceeds')
         = true
      } else {
         = false
      }
    }
}

Define the validator method of component rules (check verification when clicking submit)

&lt;van-field v-model="location" name="location" label="Place" placeholder="Please enter the business trip location" :rules="[{ required: true, validator, message: 'Please enter 7 characters within 7' }]" /&gt;

validator(val) {
	return (/\s/g, '').length &gt; 7 ? false : true
}

This is the article about vant2 automatic check form verification -validate. For more related vant2 form verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!