react + antd form表單驗證自定義驗證validator根據后台接口判斷驗證


有時候表單中的某些字段是需要調用后台接口驗證,比如賬號,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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM