文本字段验证.反应:福尔米克,是的



我有文本字段,需要对其进行验证

export default function UserInformation() {
<form className={classes.root} autoComplete="off">
<div>
<div>
<TextField
className={classes.textField}
required
id="Email"
label="Email"
defaultValue=""
/>
</div>
</div>
</form>
}

使用react进行验证的最佳方法是什么?我读过关于formik和yup的文章,但我发现就我而言,yup并不是一种有效的方式。也许有人能为前任的电子邮件提出最好的解决方案?对不起,我是新来的,所以我知道的不多。

Formik在我看来是最好的方法。npm install --save formik然后在你的代码中:

import {useFormik} from "formik";
//Has all the validations it is very flexible so edit according to your need.
const validate = values => {
const errors = {};
if (!values.password) {
errors.password = 'Required';
} else if (!(values.password.length >= 8 && values.password.length < 200)) {
errors.password = 'Must be greater then 8 characters and less then 200 ';
}
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
}
return errors;
};
export default function UserInformation() {
//Initialize formik with default values 
const formik = useFormik({
initialValues: {
email: '',
password: ''
},
validate,
//Called after you click on Submit button below
onSubmit: values => {
//DO somthing with values
}
});
return(
<form onSubmit={formik.handleSubmit} className={classes.root} autoComplete="off">
<div>
<div>
<TextField
className={classes.textField}
required
id="email"
name="email"
label="email"
defaultValue=""
//These methods are for validation and handling change.
onChange={formik.handleChange}
onBlur={formik.handleBlur}
value={formik.values.email}
/>
//Any errors of validation will be displayed here use any alert component you like
{formik.touched.email && formik.errors.email ? (
<MDBAlert color="danger" >
{formik.errors.email}
</MDBAlert>
) : null}
</div>
</div>
<button type="submit">Done</button>
</form>
);
}

您可以使用yups默认方案:

Yup.object().shape({
email: Yup.string()
.email('Invalid email!')
.required('Please, enter email'),
})

或者使用您的自定义:

Yup.object().shape({
email: Yup.string()
.matches(
/^([a-zA-Z0-9_-.]+)@([a-zA-Z0-9_-.]+).([a-zA-Z]{2,5})$/, // or any other regex
'Enter correct email'
)
.required('Please, enter phone'),
})

相关内容

  • 没有找到相关文章

最新更新