@nvidia1997/react-js-validator
This is react-wrapper for js-validator.
Please read its docs first!
How to use:
Import context related stuff
import {ValidatorProvider, ValidatorContext, ValidatorConsumer, withValidator} from "@nvidia1997/react-js-validator";
Inject the validator context
Way 1 (done in the parent component)
<SomeComponent>
<ValidatorProvider>// in this case we only need to import ValidatorProvider
<WrappedComponent/>
</ValidatorProvider>
</SomeComponent>
Way 2 (done in the target component)
function WrappedComponent(props){
return (
<div>some text</div>
);
}
export default withValidator(WrappedComponent);
In WrappedComponent
Imports
import {useValidatorContext} from "@nvidia1997/react-js-validator";
Initializing
const [text1, setText1] = useState("");
const [text2, setText2] = useState("");
const [timestamp, setTimestamp] = useState(Date.now());
const {
validator,
createOnFormSubmitHandler,
createOnValidationSuccessHandler
} = useValidatorContext();
Declaring sub validators
useEffect(() => {
validator
.string(text1, "text1Validator")
.notNull()
.notUndefined()
.maxLength(2)
validator
.string(text2, "text2Validator")
.maxLength(3)
return () => {
validator.removeValidator("text1Validator");
validator.removeValidator("text2Validator");
}
}, [validator, text1, text2, timestamp]);
Form validation
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);
};
<form onSubmit={createOnFormSubmitHandler(onSubmitSuccess, onSubmitFailure)} action="/some_action.php">
<input type="text" value={text1} onChange={onText1Change}/>
<input type="text" value={text2} onChange={onText2Change}/>
<input type="submit" value="Submit"/>
</form>
Custom validation
const onValidationSuccess = (e) => {
console.log("validation successful");
};
const onValidationFailure= (e) => {
console.log("oops, some fields have errors");
};
<button onClick={createOnValidationHandler(onValidationSuccess, onValidationFailure)}>
validate
</button>
Reset errors
<button onClick={() => {validator.reset(); }}>
reset
</button>
<span>{validator.hasErrors.toString()}</span>
Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
License
MIT