Basic introduction
-
Although React does not have built-in Form validation logic, we can use the Form component from the React component library AntDesign to do this.
-
Specifically, the Form component in AntDesign works with the Form field form.item (the container used to wrap arbitrary input controls) :
- in
Form.Item
Set validation rules to be executed when the form is submitted or the form input changesthis.props.form.validateFields()
To achieve form value verification. - in
Form.Item
Place a quilt ingetFieldDecorator
Registered form controls (child elements) to achieve form controls and form bidirectional binding, form value collection.
- in
-
The key to using the automatic data collection and validation capabilities that come with forms is to wrap the components in form.create () (portal 👉AntDesign official documentation).
-
Form.create() is a higher-order function that returns a new React component that registers, collects, and validates it by passing in a React component. The usage is as follows:
class CustomizedForm extends React.Component {}
CustomizedForm = Form.create({})(CustomizedForm);
export default CustomizedForm;
Copy the code
- the
Form.create()
Wrapped components will come with themthis.props.form
Property, which provides a number of apis to process data, as described abovegetFieldDecorator
Methods are used for bidirectional binding to forms. Once the component passes throughgetFieldDecorator
Then the value of the component will be completely modified byForm
To take over. - As we know, components can be updated in two ways: 1. 2. The status changes.
- use
Form.create()
The purpose of wrapping a component is to update the wrapped component in the first way:- Once they are
getFieldDecorator
The decorated component firesOnChange event
, triggers a forceUpdate of the parent component, which causes the wrapped component to update. - Mentioned above
Form.create({})(CustomizedForm)
.CustomizedForm
This is what we call a wrapped component.
- Once they are
- The following will be introduced
this.props.form
Property provides several apis and how to use them. Other apis can be seen in the documentation (portal 👉)AntDesign official documentation).
The API provided by the this.props. Form property
getFieldDecorator
getFieldDecorator
The purpose of the method is to register the data that needs to be collected in the instance and synchronize the registered values to thegetFieldDecorator
Modifies the form control, so the control can no longer be passedvalue
或defaultValue
Assign, its state will all be determined bygetFieldDecorator
Managed, default Settings can be usedgetFieldDecorator
In theinitialValue
. The usage is as follows:
// Syntax: getFieldDecorator(id, options) < form.item {... layout} label="Title" extra={titleExtra}>
{getFieldDecorator('name', {
rules: [
{ required: true, message: 'Remember to fill in the questions' },
{ whitespace: true, message: 'Remember to fill in the questions'},], initialValue: name, // Default setting})(<Input allowClear={true}/>)}
</Form.Item>
Copy the code
getFieldValue
getFieldValue
The getValue () method gets the value of an input control. The usage method is as follows:
let options = this.props.form.getFieldValue('name'); // The id decorated with the getFieldDecorator method is'name'Form control ofCopy the code
setFieldsValue
setFieldsValue
The ⚠️ method is used to dynamically set the values of a set of input controlscomponentWillReceiveProps
Internal use, otherwise it will cause an endless loop). The usage method is as follows:
// Set the id decorated with the getFieldDecorator method to'name'Form controls the value of this. Props. Form. SetFieldsValue ({name: undefined});Copy the code
validateFields
validateFields
The fieldNames method validates and gets a set of input field values and errors as follows (validates all components if the fieldNames parameter is null) :
/* 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) => { // ... }); // Use the validateFields method to verify that the form is completed, and then 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 tofalseTo close the dialog this.setState({visible:false}); }}); }Copy the code
Format restricted validation
- Among the many functions of forms in AntDesign, form input format validation is done through Settings
getFieldDecorator(id, options)
The validation rule parameter passed to theoptions.rules
The following is a summary of AntDesign commonly used in several form input format validation.
The input box cannot be null bound
- Example code:
{getFieldDecorator('name', {
rules: [{
required: true,
message: 'Name cannot be empty',
}],
})(<Input placeholder="Please enter a name"/ >)}Copy the code
Input box character limits
- Character length range limits:
{getFieldDecorator('password', {
rules: [{
required: true,
message: 'Password cannot be empty',
}, {
min:4,
message: 'Password must be no less than 4 characters',
}, {
max:6,
message: 'Password must be no longer than 6 characters',
}],
})(<Input placeholder="Please enter your password" type="password"/ >)}Copy the code
- Character length limit:
{getFieldDecorator('nickname', {
rules: [{
required: true,
message: 'Nickname cannot be empty',
}, {
len: 4,
message: 'Length to 4 characters',
}],
})(<Input placeholder="Please enter a nickname"/ >)}Copy the code
Custom check
- The validator attribute must return a callback for custom validation:
{getFieldDecorator('passwordcomfire', {
rules: [{
required: true,
message: 'Please enter your password again',
}, {
validator: passwordValidator
}],
})(<Input placeholder="Please enter your password" type="password"Const passwordValidator = (rule, value, callback) => {const {getFieldValue} = form;if(value && value ! == getFieldValue('password')) {
callback('Two inputs are inconsistent! '} // Always return a callback, otherwise validateFields cannot respond to callback(); }Copy the code
Whitespace space error
- If only one space is entered, an error is reported:
{getFieldDecorator('nickname', {
rules: [{
whitespace: true,
message: 'Cannot enter Spaces',
} ],
})(<Input placeholder="Please enter a nickname"/ >)}Copy the code
Pattern regular verification
- If the input is not a number, an error is displayed:
{getFieldDecorator('age', {
rules: [{
message:'Enter numbers only',
pattern: /^[0-9]+$/
}],
})(<Input placeholder="Please enter a number"/ >)}Copy the code
- The above is the full text of the introduction, if you have any questions, please leave a message.