使用antd的form表单校验+自定义form校验

antd中关于表单的操作可以说是比较齐全了,相应的api也挺完善,由于最近的几个月都是做内部系统,因此表单操作还算比较熟悉了。
首先贴一下表单的代码

<FormItem {...formItemLayout1} label='SKU ID' >
    {getFieldDecorator('add_sku_id', {
         rules: [
             { required: true, message: '请选择' },
             //自定义的检验函数
             { validator: (rule, value, callback) => this.handleConfirmSkuId(rule, value, callback) },
         ],
     },
     )(
         <Select
             allowClear
             optionFilterProp="children"
             showSearch
             placeholder="SKU ID"
         >
             {
                 skuList.length > 0 ?
                     skuList.map((item, index) => (
                         <Option key={item.sku_id} value={(item.sku_id).toString()}>{item.sku_id}</Option>
                    ))
                : null
             }
         </Select>,
     )}
 </FormItem>

图上的rules即为antd提供的检验规则

rules: [
             { required: true, message: '请选择' },
             //自定义的检验函数
             { validator: (rule, value, callback) => this.handleConfirmSkuId(rule, value, callback) },
         ]

首先注意下rules是一个数组,校验规则是一个对象,例如rules: [{ type: ‘array’, required: true, message: ‘Please select your habitual residence!’ }] – type: 'array’就表示要求输入是个数组类型数据,这样的数据类型antd给我们了

string: Must be of type string. This is the default type.
number: Must be of type number.
boolean: Must be of type boolean.
method: Must be of type function.
regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.
integer: Must be of type number and an integer.
float: Must be of type number and a floating point number.
array: Must be an array as determined by Array.isArray.
object: Must be of type object and not Array.isArray.
enum: Value must exist in the enum.
date: Value must be valid as determined by Date
url: Must be of type url.
hex: Must be of type hex.
email: Must be of type email.

常用的还有很多表单校验规则,例如pattern-正则表达式校验,enmu-枚举类型,len-字段长度等等,官网都是写的很清楚了
看下我实现的自定义校验函数

handleConfirmSkuId = (rule, value, callback) => {
    const { skuList } = this.state
    let skuInfo = skuList || []
    let len = skuInfo.length
    for (let i = 0; i < len; i++) {
        if (skuInfo[i].sku_id == value) {
            this.messageTip = '校验报错,已存在SKUID为:' + value + '的目标时效!'
            callback(this.messageTip)
            this.confirmParamsFlag = false
            return;
        }
    }
    this.messageTip = ''
    this.confirmParamsFlag = true
    callback()
}

函数校验被选中的数据是否在skuList列表中已存在,这个函数就是有三个参数,最后一个参数是返回提示信息的回调,不管这个函数如何,都一定要调用callback()。这里一开始遍历skuList时还犯了个错,就是用了map函数,但是map函数是不会中止的!!! 这样即使找到符合条件的,也不会有你想要的提示信息,因此我这里用了最保险的for循环。

你可能感兴趣的:(React,antd,form表单,自定义检验,react)