Antd-rules-custom validation rules

foreword

The company UI has a rule verification effect for form submission,
which can only be achieved by customizing rules.
As long as the input is wrong, a red border will be displayed and the submission cannot be made.
How to achieve it?
1

##Solution
Antd officially gave the case custom verification rules.
The implementation is as follows:
1. You need to customize rules
2. Customize validator
3. Fill in your rules and methods

1. Need to customize rules

<a-form :rules="rules">  

2. Custom validator

const rules: Record<string, Rule[]> = {
    
    
  barcode: [{
    
     required: true, validator: validateBarcode, trigger: 'change' }],
};

3. Fill in your rule method

/**
 * 
 * @param _rule 表单校验规则
 * @param value 
 */
const validateBarcode = async (_rule: Rule, value: string) => {
    
    
  if (value === '') {
    
    
    return Promise.reject('条形码必须为7-19位纯数字');
  } else {
    
    
    if (formState.barcode.length > 19 || formState.barcode.length < 7) {
    
    
      return Promise.reject('条形码必须为7-19位纯数字');
    }
    return Promise.resolve();
  }
};

form code

<a-form :rules="rules">     
        <a-form-item label="商品条形码" :required="!isEdit" name="barcode" >
          <div class="good-barcode">
            <a-input class="goods-barcode-len" v-model:value="formState.barcode" 
            :disabled="isEdit"
              placeholder="条形码必须为7-19位纯数字" allow-clear @change="onChange" />           
          </div>
        </a-form-item>       
      </a-form>

achieve effect

There is an attribute that matches my rules
. I need to explain that I removed it in the code and added it myself if needed.

has-feedbackThe attribute adds a feedback icon indicating the validation result to the input box.

1
does not comply with my rules
2

Guess you like

Origin blog.csdn.net/Life_s/article/details/129731032