Ant Design custom validations for Form components

1. Form verification

Put the Validator in the rules array

< form. Item label=" name "> {getFieldDecorator('userName', {rules: [{required: true, message: 'Please enter name! ',},{validator: This.checkval}]})(<Input placeholder=" placeholder "/>)} </ form.item >Copy the code

2. Customize the verification method

Call method: Calls the interface when value changes, and calls the callback function based on the value returned by the interface

checkVal = (rule, value, callback) => { if (! value) { callback(); } const { dispatch } = this.props; Dispatch ({type: 'XXXX/XXXXXX ', payload: value,}). Then (function (res) {if (" callback ") {callback(); } else {callback(" condition does not meet the hint "); }}); }Copy the code

The method takes three arguments: rule is the rule, value is the value you input, and callback is a callback function

Write callback() regardless of whether or not callback returns the prompt. Otherwise, write an empty callback()

The new ANTD form field validation method returns a Promise object instead of a callback

Const checkVal = (_, val) => {if (" satisfy condition ") {return promise.resolve (); } else {return promise. reject(" condition not fulfilled "); }};Copy the code

3,debounceImage stabilization

To reduce the number of requests, you need to write your own Debounce anti-shake method because validation calls to the interface are required

If an event is triggered within n seconds, the function execution time is recalculated

debounce = (fn, delay=500) => { return (... rest) => { let args = rest; if (this.timerId) clearTimeout(this.timerId); this.timerId = setTimeout(() => { fn.apply(this, args) }, delay) } }Copy the code

Modify the form validation call method

< form. Item label=" name "> {getFieldDecorator('userName', {rules: [{required: true, message: 'Please enter name! ',},{validator: This. Debounce (this.checkval, 500)}]})(<Input placeholder=" />)} </ form.item >Copy the code