Validation of complex forms React. Part 1
3r3-31. First you need to install the 3r3r6646 component. react-validation-boo [/b] , I assume that you are familiar with react and know how to configure. 3r3885.
3r3885.
npm install react-validation-boo 3r3885.
3r3885.
In order not to talk a lot, I will immediately give you a small sample code. 3r3885.
3r3885.
3r3653. import React, {Component} from 'react';
import {connect, Form, Input, logger} from 'react-validation-boo';
class MyForm extends Component {
sendForm = (event) => {
event.preventDefault ();
if (this.props.vBoo.isValid ()) {
console.log ('Get the values entered and send them to the server', this.props.vBoo.getValues ());
} else {
console.log ('We will output errors to the console', this.props.vBoo.getErrors ());
}
};
getError = (name) => {
return this.props.vBoo.hasError (name)?
{this.props.vBoo.getError (name)}
: '';
};
render () {
return
3r33824.
3r3752.
{this.getError ('name')}
3r33894.
3r33836.
{this.props.vBoo.isValid ()? 'You can send': 'Be careful !!!'}
3r33838.
3r33841.
}
}
export default connect ({
rules: () => (3r33898.[
['name', 'required'],
]
),
middleware: logger
}) (MyForm);
3r3883. 3r3884. 3r3885.
3r3885.
Let's break this code down. 3r3885.
3r3885.
Let's start with the function 3r3646. connect [/b] , we pass our validation rules and other advanced parameters to it. By calling this method we get a new function in which we transfer our component ( MyForm ), So that it will receive in props necessary methods of work with the validation of forms. 3r3885.
3r3885.
In function 3r3646. render [/b] of our component, we return the component Form which we connect with the rules of validation connect = {this.props.connect} . This necessary design to Form knew how to validate nested components. 3r3885.
3r3-300. The input field that we will check, we have passed the validation rules to connect in property 3r3646. rules [/b] . In our case, this is name must not be empty ( required ). 3r3885.
3r3885.
We are also in 3r3646. connect [/b] handed over 3r3646. middleware: logger [/b] in order to see the validation in the console. 3r3885.
3r3885.
In 3r3646. props [/b] of our component, we got a set of functions: 3r3r885.
3r3885.
3r3-3598.
3r3612. vBoo.isValid () - returns 3r3r6646. true [/b] if all input components have been validated 3r3-3617.
3r3612. vBoo.hasError (name) - returns 3r3r6646. true [/b] if the component with property name not validin
3r3612. vBoo.getError (name) - for the component with property name It returns the text of the error 3r31717.
3r3619. 3r3885.
Now we will gradually complicate, for a start in 3r3r6646. connect [/b] let's pass the language in order to be able to change the validation rules depending on the language, and also add additional fields and validation rules. 3r3885.
3r3885.
3r3653. import React, {Component} from 'react';
import {connect, Form, Input, InputCheckbox} from 'react-validation-boo';
class MyForm extends Component {
sendForm = (event) => {
event.preventDefault ();
if (this.props.vBoo.isValid ()) {
console.log ('Get the values entered and send them to the server', this.props.vBoo.getValues ());
} else {
console.log ('We will output errors to the console', this.props.vBoo.getErrors ());
}
};
getError = (name) => {
return this.props.vBoo.hasError (name)?
{this.props.vBoo.getError (name)}
: '';
};
render () {
return
3r33824.
{this.props.vBoo.getLabel ('name')}:
3r3752.
{this.getError ('name')}
3r33894.
3r33824.
{this.props.vBoo.getLabel ('email')}:
3r33762.
{this.getError ('email')}
3r33894.
3r33824.
{this.props.vBoo.getLabel ('remember')}:
3r33418.
{this.getError ('remember')}
3r33894.
3r33836.
{this.props.vBoo.isValid ()? 'You can send': 'Be careful !!!'}
3r33838.
3r33841.
}
}
export default connect ({
rules: (lang) => {
let rules =[
[
['name', 'email'],
'required',
{3rr3898. error: '% name% should not be empty'
}
], 3r33898. W2w2w227.
]; 3-333898. 3r3-33898. Rules.push (['remember', lang === 'ru' ? 'required': 'valid']);
Return rules;
}, 3r33898.
Email: 'Email',
Remember: 'Remember'
}),
Lang: 'en'
}) (MyForm);
3r3883. 3r3884. 3r3885.
In this example, the checkbox is remember 3r3r664 must be installed in Russian. required [/b] , and on others it is always valid valid . 3r3885.
3r3885.
We also referred to 3r3646. connect [/b] function 3r3r6646. labels (lang) [/b] which returns the name of the fields in a readable form. 3r3885.
3r3885.
In 3r3646. props [/b] your component, there is a function getLabel (name) which returns the value passed by the function 3r3646. labels [/b] or if there is no such value, it returns name . 3r3885.
3r3885.
3r33545. The basic components of vBoo
3r3885.
Form , Input , InputRadio , InputCheckbox , Select , Textarea . 3r3885.
3r3885.
3r3653. import React, {Component} from 'react';
import {connect, Form, Input, Select, InputRadio, InputCheckbox, Textarea} from 'react-validation-boo';
class MyForm extends Component {
sendForm = (event) => {
event.preventDefault ();
if (this.props.vBoo.isValid ()) {
console.log ('Get the values entered and send them to the server', this.props.vBoo.getValues ());
} else {
console.log ('We will output errors to the console', this.props.vBoo.getErrors ());
}
};
getError = (name) => {
return this.props.vBoo.hasError (name)?
{this.props.vBoo.getError (name)}
: '';
};
render () {
return
3r33824.
{this.props.vBoo.getLabel ('name')}:
3r3752.
{this.getError ('name')}
3r33894.
3r33824.
{this.props.vBoo.getLabel ('email')}:
3r33762.
{this.getError ('email')}
3r33894.
3r33824.
{this.props.vBoo.getLabel ('gender')}:
3r3772.
3r3774. Your floor
3r3r7777. Male
3r33780. Women's
{this.getError ('gender')}
3r33894.
3r33824.
3r33824. {this.props.vBoo.getLabel ('familyStatus')}:
3r33824.
single 3r3827.
3r33894.
3r33824.
3r33383.
cohabitation
3r33894.
3r33824.
marriage
3r33894.
{this.getError ('familyStatus')}
3r33894.
3r33824.
{this.props.vBoo.getLabel ('comment')}:
3r33737. 3r33737.
{this.getError ('comment')}
3r33894.
3r33824.
{this.props.vBoo.getLabel ('remember')}:
3r33418.
{this.getError ('remember')}
3r33894.
3r33836.
{this.props.vBoo.isValid ()? 'You can send': 'Be careful !!!'}
3r33838.
3r33841.
}
}
export default connect ({
rules: () => ([
[
['name', 'email'],
'required',
{3rr3898. error: '% name% should not be empty'
} 3r33898.],
['email', 'email']} ,
W2w2w26., 'Valid']
]),
Labels: () => ({
Name: 'Name',
Email: 'E-mail', 3r33898. Gender: 'Sex',
familyStatus: 'Marital status',
comment: 'Comment',
remember: 'remember'
}), 3r3r9898. lang: 'en'
}) (MyForm);
3r3883. 3r3884. 3r3885.
3r33545. Validation Rules 3r33546. 3r3885.
Let's take a look at how to write your own validation rules. 3r3885.
In order to write a rule you need to create a class that will be inherited from the class validator . 3r3885.
3r3885.
3r3653. import {validator} from 'react-validation-boo';
class myValidator extends validator {
/3r3r9898. * name - the name of the field, if there is a label, then it will be passed to
* value - the current value of the field
* params - parameters that were passed by the 3rd argument to the validation rules (rules)
* /
validate (name, value, params) {
let lang = this.getLang ();
let pattern = /^ d + $ /;
if (! pattern.test (value)) {
let error = params.error || 'Error for field% name% with value% value%';
error = error.replace ('% name%', name);
error = error.replace ('% value%', value);
this.addError (error);
}
}
}
export default myValidator;
3r3883. 3r3884. 3r3885.
Now we connect our validator to the form. 3r3885.
3r3653. import myValidator from 'path /myValidator';
//3r39898.
export default connect ({
rules: () => ([
[
'name',
'required',
{
error: '%name% не должно быть пустым'
}
],
[
'name',
'myValidator',
{
error: 'это и будет params.error'
}
]
]),
labels: () => ({
name: 'Name'
}),
validators: {
myValidator
},
lang: 'en'
}) (MyForm);
3r3883. 3r3884. 3r3885.
In order not to prescribe all your validation rules every time, we create a separate file where they will be registered and connect it to 3r3r6646. validators: `import 'file-validation'` [/b] . And if there are any special rules for this form, then validators: Object.assign ({}, `import 'file-validation'`, {}) 3r3885.
3r3885.
3r33545. Scenarios 3r33546. 3r3885.
Consider cases when we need to change the validation rules depending on the actions performed on the form. 3r3885.
3r3885.
By default, we have a script called default , in the rules we can prescribe under what scenario to conduct this validation. 3r3885.
3r3885.
If the script is not specified, then validation will be performed for all scripts. 3r3885.
3r3885.
3r3653. rules = () => ([
[
'name',
'required',
{
error: '%name% не должно быть пустым'
}
], 3r3-39898.[
'name',
'myValidator',
{
scenario:['default', 'scenario1']
}
], 3r3-39898.[
'email',
'email',
{
scenario: 'scenario1'
}
]3r39898.]) 3r3-39898. 3r3883. 3r3884. 3r3885.
Through property 3r3646. props [/b] our component passed functions:
3r3885.
3r3-3598.
3r3612. vBoo.setScenario (scenario) - installs the script. scenario 3r3r7647. maybe both a string and an array, if we have several
scripts active at once.
3r3612. vBoo.getScenario () - returns the current script or array of scripts
3r3612. vBoo.hasScenario (name) - shows whether this script is currently installed, name line
3r3619. 3r3885.
Let's add an object in our form. scenaries in which we will store all possible scenarios, true script active, 3r3r6646. false not. 3r3885.
3r3885.
As well as features 3r3646. addScenaries [/b] and 3r3646. deleteScenaries [/b] that will add and delete scripts. 3r3885.
3r3885.
If we have a “marital status” selected “cohabitation” or “marriage”, then we add a comment field and of course this field should be validated only in this case, the script ' scenario-married '. 3r3885.
3r3885.
If the “Advanced” checkbox is set for us, then we add additional fields that will become mandatory, the script ' scenario-addition '. 3r3885.
3r3885.
3r3653. import React, {Component} from 'react';
import {connect, Form, Input, Select, InputRadio, InputCheckbox, Textarea} from 'react-validation-boo';
class MyForm extends Component {
constructor () {
super ();
this.scenaries = {
'scenario-married': false,
'scenario-addition': false
}
}
changeScenaries (addScenaries =[], deleteScenaries =[]) {
addScenaries.forEach (item => this.scenaries[item]= true);
deleteScenaries.forEach (item => this.scenaries[item]= false);
let scenario = Object.keys (this.scenaries)
.reduce ((result, item) => this.scenaries[item]? result.concat (item): result,[]);
this.props.vBoo.setScenario (scenario);
}
addScenaries = (m =[]) => this.changeScenaries (m,[]);
deleteScenaries = (m =[]) => this.changeScenaries ([], m);
sendForm = (event) => {
event.preventDefault ();
if (this.props.vBoo.isValid ()) {
console.log ('Get the values entered and send them to the server', this.props.vBoo.getValues ());
} else {
console.log ('We will output errors to the console', this.props.vBoo.getErrors ());
}
};
getError = (name) => {
return this.props.vBoo.hasError (name)?
{this.props.vBoo.getError (name)}
: '';
};
changeFamilyStatus = (event) => {
let val = event.target.value;
if (val! == '1') {3r33898. this.addScenaries (['scenario-married'])
} else {
this.deleteScenaries (['scenario-married']);
}
};
changeAddition = (event) => {3r33898. let check = event.target.checked;
if (check) {
this.addScenaries (['scenario-addition'])
} else {
this.deleteScenaries (['scenario-addition']);
}
};
getCommentContent () {
if (this.props.vBoo.hasScenario ('scenario-married')) {
return (
{this.sect .)
}
return '';
}
getAdditionContent () {
if (this.props.vBoo.hasScenario ('scenario-addition')) {
return (
3r3826. {this. 3) 3r???. ;
}
return '';
}
render () {
return
3r33824.
{this.props.vBoo.getLabel ('name')}:
3r3752.
{this.getError ('name')}
3r33894.
3r33824.
{this.props.vBoo.getLabel ('email')}:
3r33762.
{this.getError ('email')}
3r33894.
3r33824.
{this.props.vBoo.getLabel ('gender')}:
3r3772.
3r3774. Your floor
3r3r7777. Male
3r33780. Women's
{this.getError ('gender')}
3r33894.
3r33824.
3r33824. {this.props.vBoo.getLabel ('familyStatus')}:
3r33824.
3r33795.
single 3r3827.
3r33894.
3r33824.
3r3804.
cohabitation
3r33894.
3r33824.
marriage
3r33894.
{this.getError ('familyStatus')}
3r33894.
{this.getCommentContent ()}
3r33824.
{this.props.vBoo.getLabel ('addition')}:
{this.getError ('addition')}
3r33894.
{this.getAdditionContent ()}
3r33836.
{this.props.vBoo.isValid ()? 'You can send': 'Be careful !!!'}
3r33838.
3r33841.
}
}
export default connect ({
rules: () => ([
[
['name', 'gender', 'familyStatus', 'email'],
'required',
{3rr3898. error: '% name% should not be empty'
}
],
['email', 'email']} 3r39898.], 3rr3898.['email', 'email']} , 3r3r9898. W2w2w228.,
W2w2w229.,
W2w2w230.,
]), 3rr3898. Labels: () => ({
Name: 'Name', 3) gender: 'Sex',
familyStatus: 'Marital status',
comment: 'Comment',
addition: 'Extras',
place: 'Location'
}),
lang: 'en'
}) (MyForm);
3r3883. 3r3884. 3r3885.
In order not to make the article very large, I will continue in the next one, where I will write how to create my components (for examplemeasure calendar or inputSearch) and validate them, how to associate with redux and more. 3r33894.
3r33891. ! function (e) {function t (t, n) {if (! (n in e)) {for (var r, a = e.document, i = a.scripts, o = i.length; o-- ;) if (-1! == i[o].src.indexOf (t)) {r = i[o]; break} if (! r) {r = a.createElement ("script"), r.type = "text /jаvascript", r.async =! ? r.defer =! ? r.src = t, r.charset = "UTF-8"; var d = function () {var e = a.getElementsByTagName ("script")[0]; e.parentNode.insertBefore (r, e)}; "[object Opera]" == e.opera? a.addEventListener? a.addEventListener ("DOMContentLoaded", d,! 1): e.attachEvent ("onload", d ): d ()}}} t ("//mediator.mail.ru/script/2820404/"""_mediator") () (); 3r33892.
3r33894.
It may be interesting
weber
Author19-11-2018, 08:12
Publication DateDevelopment / ReactJS
Category- Comments: 0
- Views: 282