[英]How can I can validate form fields using sync and async validation rules together on onBlur?
I have form with validation on onBlur
and onKeyDown
.我有对onBlur
和onKeyDown
进行验证的表单。 My problem is to implement validation of email field.我的问题是实现 email 字段的验证。 The task is to check this field on frontend side using regex expression and in case of truth I should check it on backend for existing in database using existing API point.任务是使用正则表达式在前端检查该字段,如果是真的,我应该使用现有的 API 点在后端检查它是否存在于数据库中。 I implement form with function useForm
that has initialValues
(object of initial values for the form fields), callback
(function that invokes after pressing Submit), validate
(function that validates every form field) as parametres.我使用 function useForm
实现表单,它具有initialValues
(表单字段的初始值对象)、 callback
(按下提交后调用的函数)、 validate
(验证每个表单字段的函数)作为参数。
const useForm = (initialValues, callback, validate) => {
const [values, setValues] = useState(initialValues);
const [errors, setErrors] = useState({});
const performValidation = (name) => {
const validationErrors = validate({ [name]: values[name] });
setErrors({...errors, ...validationErrors} );
};
const handleKeyDown = (event) => {
if(event.which === ENTER_KEY_CODE || event.which === TAB_KEY_CODE)
performValidation(event.target.name);
};
const handleBlur = ({ target : { name } }) => {
performValidation(name);
};
.....
return {
values,
errors,
handleChange,
handleKeyDown,
handleBlur,
}
}
Form React usage:表单反应用法:
const {
values, errors, handleChange, handleKeyDown, handleBlur, handleSubmit,
} = useForm(initialValuesForRegistration, submitHandler, formValidationFunction);
<form onSubmit={handleSubmit} noValidate>
<Input
type='text'
name={formFieldNames.email}
value={values.email}
errMessage={errors.email}
onChange={handleChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
/>
My email validation function:我的 email 验证 function:
import validateEmail from 'filter-validate-email';
const checkEmail = (value) => {
if(!validateEmail(value))
return FORM_EMAIL_INVALID;
// HERE I need to async check with API point call
};
Could you please suggest me some ideas how I can implement this issue?您能否建议我一些想法如何实现这个问题?
You can validate email like this:-您可以像这样验证 email:-
handleValidation(){
let fields = this.state.email;
let errors = {};
let formIsValid = true;
if(!fields["email"]){
formIsValid = false;
errors["email"] = "Cannot be empty";
}
if(typeof fields["email"] !== "undefined"){
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') == -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
formIsValid = false;
errors["email"] = "Email is not valid";
}
}
this.setState({errors: errors});
return formIsValid;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.