我是React JS的新手。React JS中是否有任何表单验证库,例如angular具有反应形式和模板驱动形式,以及它自己的一组验证规则,例如有效,脏,原始。
答案 0 :(得分:1)
我建议使用Formik,它非常简单和完整。在github上有1万4千颗星星,很好!!
答案 1 :(得分:0)
使用joi浏览器
https://www.npmjs.com/package/joi-browser
validate = () => {
const options = { abortEarly: false }; //By default, Joi terminates validation as soon as it finds an error. This is called abort early.
const { error } = Joi.validate(this.state.data, this.schema, options);
//you can write like below to see what Joi.validate() returns
//const result = Joi.validate(this.state.data, this.schema, options)
//console.log(result)
//It returns an object which has “error” object. In this object we have details
which is an array of objects. Each object in the “details‘ has message and path
property.
if (!error) return null;
const errors = {};
//path is an array and the first element is the name of the target
property.username or password
for (let item of error.details) {
errors[item.path[0]] = item.message;
console.log(errors);
return errors;
}
};
const schema = {
username: Joi.string()
.required()
.label("Username"),//this is to display "Username" instead of "username" in the error message
password: Joi.string()
.required()
.label("Password")
};
我们总是在handleSubmit中验证表单
handleSubmit = e => {
e.preventDefault();
const errors = this.validate();
console.log(errors);
this.setState(() => ({ errors: errors || {} }));
if (errors) return;
};
答案 2 :(得分:0)
React js中的表单验证-
validate = () => { this.setState({ nameError: "", emailError: "", ageError: "", genderError: "", courseError: "", imageError: "" });
let error = false;
if (this.state.name === "") {
this.setState({ nameError: "Name is required" });
error = true;
}
if (this.state.name !== "" && this.state.name.length < 5) {
this.setState({
nameError: "Name should be greater than 5 characters"
});
error = true;
}
if (this.state.email === "") {
this.setState({ emailError: "Email is required" });
error = true;
}
if (this.state.email !== "" && !myConstants.Email_Reg_Expression.test(this.state.email)) {
this.setState({ emailError: "Email is invalid" });
error = true;
}
if (this.state.age === "") {
this.setState({ ageError: "Age is required" });
error = true;
}
if (
this.state.age !== "" &&
Number.isInteger(parseInt(this.state.age)) === false
) {
this.setState({ ageError: "Enter only numbers" });
error = true;
}
if (this.state.gender === "") {
this.setState({ genderError: "Gender is required" });
error = true;
}
if (this.state.course === "0") {
this.setState({ courseError: "Course is required" });
error = true;
}
if (this.state.image === "") {
this.setState({ imageError: "Image is required" });
error = true;
}
if (error) {
return false;
}
return true;
};