#### This is react-wrapper for [js-validator](https://www.npmjs.com/package/@nvidia1997/js-validator). #### Please read its docs first!
#### This is react-wrapper for js-validator.
#### Please read its docs first!
javascript
import {ValidatorProvider, ValidatorContext, ValidatorConsumer, withValidator} from "@nvidia1997/react-js-validator";
`#### Inject the validator context
#### Way 1 (done in the parent component)
`javascript
// not necessary to wrap ValidatorProvider
// in this case we only need to import ValidatorProvider
`#### Way 2 (done in the target component)
`javascript
function WrappedComponent(props){
return (
some text
);
}export default withValidator(WrappedComponent);
`#### In WrappedComponent
#### Imports
`jsx
import {useValidatorContext} from "@nvidia1997/react-js-validator";
`#### Initializing
`jsx
const [text1, setText1] = useState("");
const [text2, setText2] = useState(""); // timestamp variable is needed only if you're using allowNull, allowUndefined, notRequired validations and validation on change at the same time
const [timestamp, setTimestamp] = useState(Date.now());
const {
validator,
createOnFormSubmitHandler,
createOnValidationSuccessHandler
} = useValidatorContext();
`#### Declaring sub validators
`jsx
useEffect(() => {
validator
.string(text1, "text1Validator")
.notNull()
.notUndefined()
.maxLength(2)
//.validate(false); // uncomment if you want the validations to occur on text change validator
.string(text2, "text2Validator")
.maxLength(3)
//.validate(); //only last validate method must be without "false" as param. This will fire onStateChanged only once.
return () => {
validator.removeValidator("text1Validator");//remove validators when dismounting components to avoid hidden validation errors
validator.removeValidator("text2Validator");
}
}, [validator, text1, text2, timestamp]);// if we're not doing validation on change, timestamp is not required
`#### Form validation
`jsx
const onSubmitSuccess = (e) => {
console.log("form submitted");
}; const onSubmitFailure = (e) => {
console.log("form NOT submitted, validation errors occurred");
};
const onText1Change = (e) => {
setText1(e.target.value);
};
const onText2Change = (e) => {
setText2(e.target.value);
};
`#### Custom validation
`jsx
const onValidationSuccess = (e) => {
console.log("validation successful");
}; const onValidationFailure= (e) => {
console.log("oops, some fields have errors");
};
`#### Reset errors
`jsx
{validator.hasErrors.toString()}
``Please make sure to update tests as appropriate.