antd form表单验证自定义验证validator根据后台接口判断验证

聂华翰
2023-12-01

有时候表单中的某些字段是需要调用后台接口验证,比如账号,ID之类的.这时候页面需要根据后台返回结果提示

// 验证账号是否已经被添加过
  const checkAccount = (value: string | number) => { // 这个是rules自定义的验证方法
    return new Promise((resolve, reject) => {  // 返回一个promise
      checkedAccount({ account: value }).then(res => { // 这个是后台接口方法
        if (res.responseCode === '000000') {
          console.log(11, res.data)
          resolve(res.data)
        } else resolve(false)
      }).catch(error => {
        reject(error)
      })
    })
  }

 <FormItem
     name='account'
     label='账号'
     rules={[
     { required: true, message: '请输入账号!' },
     {
        validator: (rule, value, callback) => {
          checkAccount(value).then(res => {
             if (res) {
                 // console.log(33, res)
                  callback()
              } else {
                  callback('账号已存在')
                      }
               })
         },
      },
      ]}
 >
   <Input placeholder='' />
 </FormItem>

页面(注意放在data()里)

  data() {

    let {  
 
      validateTimeBegin2,
 
    } = require('../validator/HrGroup')


    let validatePass = (rule, value, callback) => {
      if (value === '' || value === undefined) {
        callback(new Error('请输入编码!'));
      } else {
        this.validateFieldShiftCode(rule, value).then(res => {
          // console.log(33, res)
          if (res) {
              callback(res)
          } else {
              callback()
          }
        })        
      }
    };

   return {
      shiftName:'变化',
      validatorRules: {
        shiftCode: [{ validator: validatePass, trigger: 'blur'}],
        range2OnTime: [{ required: true,validator: (rule, value, callback) => { validateTimeBegin2(rule, value, this, callback) }, trigger: 'change'}],
      },
   }
   
}

../validator/HrGroup.js


// 自定义校验文件同时载入this
let validateTimeBegin2 = (rule, value, that, callback) => {
    console.log(value,5)
    that.model.shiftName = value  // 双向绑定
    if (value === '' || !value) {
      callback(new Error('请输入时间!'));
    } else {
       
    }
};




export {

  validateTimeBegin2,

}

bug记录:采用timePicker时间记得初始值必须是''不可以为null(不然表单校验不提示红字)提交接口是可以手动赋值null

callback();return 默认检验通过

 类似资料: