简体   繁体   中英

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 . My problem is to implement validation of email field. 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. 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.

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:

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:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM