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

时间:2019-11-18 08:45:04

标签: javascript reactjs forms validation

我有一个在onBluronKeyDown上经过验证的表格。我的问题是实施电子邮件字段的验证。任务是使用regex表达式在前端侧检查此字段,如果属实,我应该使用现有的API点在后端检查它是否存在于数据库中。 我用函数useForm实现了表单,该函数具有initialValues(表单域初始值的对象),callback(按Submit之后调用的函数),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用法:

  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}
        />

我的电子邮件验证功能:

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
};

能否请您提出一些想法,以解决该问题?

1 个答案:

答案 0 :(得分:0)

您可以像这样验证电子邮件:-

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;
   }