简体   繁体   English

如何在 onBlur 上同时使用同步和异步验证规则来验证表单字段?

[英]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 .我有对onBluronKeyDown进行验证的表单。 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.

相关问题 如何使用JavaScript验证表单中的多个字段? - How can I validate multiple fields in a form using Javascript? 如何根据按钮单击验证表单字段? - How can i validate form fields based on button click? JavaScript表单验证-无法验证多个字段 - Javascript form validation - can't validate multiple fields 如何在客户端验证中验证二变量规则? - How can I validate two-variable rules in client-side validation? 如何在表单onblur中验证日期 - How to validate Date in form onblur 如果每次更改字段数,如何验证表单数据? 我正在使用 Ajax 发送表单数据 - How can I validate form data if the number of fields changed every time? I am sending form data using Ajax React:如何将表单验证从所有字段的 onSubmit 验证更改为表单中每个字段的 onBlur 即时验证? - React: How to change form validation from onSubmit validation for all fields, to onBlur instant validation for each field in the form? 如何使用jQuery验证Laravel验证规则 - How to validate laravel validation rules using jquery 尝试通过验证制作 Formik 多步骤。 如何验证字段? - Trying to make a Formik multistep with validation. How can I validate fields? jQuery validate,如何为动态生成的字段制定验证规则? - jQuery validate , how to make validation rules for dynamically generated fields?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM