0.1.6 • Published 6 years ago
react-custom-validator v0.1.6
React Custom Validator
- Github https://github.com/shaun2099/react-custom-validator
- No wrapped react-dom components required, validate on state other than input, fully customized validator.
- You can use some default validators e.g.
Requied
,Email
,MinLength
,MaxLength
,Number
,True
,SameAs
. - You can create your own validators as you like.
Step 1, import component and initialize a validation summary in constructor
import { ValidationMessage, ValidationSummary, Required, Email, MinLength, MaxLength, Number, True, SameAs } from "react-custom-validator";
constructor(props) {
this.vs = ValidationSummary();
}
Step 2 - use ValidationMessage after html input or wherever you like
<input type="text" name="username" onChange={this.onChange} />
<ValidationMessage validators={[Required]} data={this.state.username} vs={this.vs} sync={true} tag="username" errStyle="text-danger" eleStyle="invalid" />
<button type="button" onClick={this.validate}>Submit</button>
validators
a list of validators predefined, you can have multiple Required, Email, MinLength(20), you can pass error message Email("invalid email format"), MaxLength(10, "Max length is 10")data
the value you want to validate, this should be a state.value, not tested with this.props.value.vs
the validation summary it hooks on, so set it to this.vs.sync
optional, set to true if you want to do validation while typing; set to false or remove this attribute if you only want to validate this field when submit formltag
optional, the html element name or id tag="#id". If this field is set you can then update your control's style when validation fails.errStyle
optional, the style of ValidationMessage, usually it is a red color styleeleStyle
optional, the style of html element when validation fails, usually it is a red border style
Step 3 - handle validation summary
validate = () => {
let valid = this.vs.isValid();
if (!vallid)
this.setState({ errorMessages: this.vs.getMessages() });
else
console.log("Validation succeed");
}
Handle your final check during form submission.
this.vs.getMessages()
returns a array of messages for all errors, returns [] if no error.
You are all set until now. If you want create your own validator:
Customized validator
export const OnlyLetter = (message) => ({
validate: (value) => {
if (!value) return true;
return /^[a-zA-Z]*$/.test(value);
},
errMessage: () => {
return message ? message : "Only letters are allowed";
}
});