Basic Introduction
-
Although react does not have built-in form validation logic, we can do this using the form component Form in the react component library AntDesign s.
-
Specifically, the form component Form in AntDesign is used in conjunction with the form field Form.Item, a container that encapsulates any input control:
- Set validation rules in Form.Item to validate form values by executing this.props.form.validateFields() when form submission or form input changes.
- Place a form control (child element) registered by getFieldDecorator in Form.Item to bind the form control to the form in both directions and collect form values.
-
The key to using Form's built-in automatic data collection and validation capabilities is the need to use Form.create() to wrap components (portal_ Official AntDesign s Documentation).
-
Form.create() is a higher-order function that returns a new react component with registration, collection, and verification capabilities by passing in a react component.Use it as follows:
class CustomizedForm extends React.Component {} CustomizedForm = Form.create({})(CustomizedForm); export default CustomizedForm; //Copy Code
- Components wrapped in Form.create() come with the this.props.form property, which provides many API s to process data, such as the getFieldDecorator method described above for bidirectional binding to forms.Once a component has been modified by a getFieldDecorator, the value of that component will be completely taken over by Form.
- We know that there are two ways to update a component: 1. the parent component updates; 2. its own state changes.
- The purpose of using Form.create() to wrap components is to update the wrapped components in the first way:
- Once a component decorated with a getFieldDecorator triggers the onChange event, a forceUpdate of the parent component triggers the update of the wrapped component.
- Form.create ({}) (CustomizedForm) mentioned above, CustomizedForm is what we call wrapped components.
- The following describes several API s and how to use them provided by this.props.form property, while others can view the documentation in detail (Portal_ Official AntDesign s Documentation).
API provided by this.props.form property
getFieldDecorator
- The purpose of the getFieldDecorator method is to register the data that needs to be collected in an instance and synchronize the registered values to a form control decorated with getFieldDecorator, so the control can no longer be assigned via value or defaultValue, and its state will be managed entirely by getFieldDecorator, with default values setYou can use the initialValue in the getFieldDecorator.Use it as follows:
// Syntax: getFieldDecorator(id, options) <Form.Item {...layout} label="subject" extra={titleExtra}> {getFieldDecorator('name', { rules: [ { required: true, message: 'Remember to fill in the title' }, { whitespace: true, message: 'Remember to fill in the title' }, ], initialValue: name, // Default Value Settings })(<Input allowClear={true}/>)} </Form.Item> //Copy Code
getFieldValue
- The getFieldValue method is used to get the value of an input control.Use it as follows:
let options = this.props.form.getFieldValue('name'); //Form control with id'name'modified using the getFieldDecorator method Copy Code
setFieldsValue
- The setFieldsValue method is used to dynamically set the values of a set of input controls (Caution: Do not use it inside the componentWillReceiveProps, otherwise it will result in an infinite loop).Use it as follows:
//Set the value of a form control with id'name'decorated with the getFieldDecorator method this.props.form.setFieldsValue({ name: undefined }); Copy Code
validateFields
- The validateFields method is used to check and get values and errors for a set of input fields using the following (if the fieldNames parameter is empty, check all components):
/* Type: ( [fieldNames: string[]], [options: object], callback(errors, values) ) => void */ const { form: { validateFields } } = this.props; validateFields((errors, values) => { // ... }); validateFields(['field1', 'field2'], (errors, values) => { // ... }); validateFields(['field1', 'field2'], options, (errors, values) => { // ... }); // Verify that the form is complete by using the validateFields method and submit the add action. handleOk = () => { const { dispatch, form: { validateFields } } = this.props; validateFields((err, values) => { if (!err) { dispatch({ type: 'cards/addOne', payload: values, }); // Reset the `visible` property to false to close the dialog this.setState({ visible: false }); } }); } //Copy Code
Format Restriction Validation
- Forms in AntDesignhave many functions, among which form input format validation is achieved by setting the check rule parameter options.rules passed in the getFieldDecorator(id, options) method. Here is a summary of several forms input format validation commonly used in AntDesigns.
Input box cannot be empty limit
- Instance code:
{getFieldDecorator('name', { rules: [{ required: true, message: 'Name cannot be empty', }], })(<Input placeholder="Please enter a name" />)} //Copy Code
Input box character limit
- Character length range limit:
{getFieldDecorator('password', { rules: [{ required: true, message: 'Password cannot be empty', }, { min:4, message: 'Password cannot be less than 4 characters', }, { max:6, message: 'Password cannot be greater than 6 characters', }], })(<Input placeholder="Please input a password" type="password"/>)} //Copy Code
- Character length limit:
{getFieldDecorator('nickname', { rules: [{ required: true, message: 'Nickname cannot be empty', }, { len: 4, message: 'Length of 4 characters', }], })(<Input placeholder="Please enter a nickname" />)} //Copy Code
Custom Check
- The validator attribute custom validation must return a callback:
{getFieldDecorator('passwordcomfire', { rules: [{ required: true, message: 'Please enter your password again', }, { validator: passwordValidator }], })(<Input placeholder="Please input a password" type="password"/>)} // Password verification const passwordValidator = (rule, value, callback) => { const { getFieldValue } = form; if (value && value !== getFieldValue('password')) { callback('The two inputs are inconsistent!') } // Always return a callback, otherwise validateFields cannot respond callback(); } //Copy Code
whitespace space space space error
- If only one space is entered, an error will be reported:
{getFieldDecorator('nickname', { rules: [{ whitespace: true, message: 'Cannot enter spaces', } ], })(<Input placeholder="Please enter a nickname" />)} //Copy Code
pattern regular validation
- If a number is not entered, an error is prompted:
{getFieldDecorator('age', { rules: [{ message:'Only numbers can be entered', pattern: /^[0-9]+$/ }], })(<Input placeholder="please enter a number" />)} //Copy Code
- The above is the introduction of the full text, if you have any questions, you are welcome to leave a message.
Author: Little Black Front End
Link: https://juejin.im/post/5d63c252f265da03aa257b8c
Source: Excavation
Copyright belongs to the author.For commercial reprinting, please contact the author for authorization. For non-commercial reprinting, please indicate the source.