0

I want to trigger the HTML validation of a form field before submitting it (type email here). More precisely when losing focus. From what I gathered it's not possible to trigger the built-in validation without submitting the form, hence this 'hack'. I'm using react 16.4.1 and TypeScript.

Here is the code:

The constructor:

private submitRef: React.RefObject<HTMLInputElement>;
public constructor(props: IProps) {
    super(props);
    this.submitRef = React.createRef();
}

The render method:

 <form onSubmit={this.handleSubmit} name="login">
     <input
         className="input"
         id="email"
         name="login.email"
         value={this.state.login.email}
         onChange={this.handleChange}
         placeholder="Email"
         type="email"
         onBlur={this.checkEmailValidity}
         required={true}
     />
     <input type="submit" value="Login" ref={this.submitRef} />
 </form>

The checkEmailValidity method:

@autobind
private checkEmailValidity(event: React.FormEvent<HTMLInputElement>) {
    if (!event.currentTarget.checkValidity()) {
        this.submitRef.current!.click();
    }
}

So when losing focus, the checkEmailValidity method is called, and verifies that the input is indeed not valid. I checked that the reference to the current element is returning the correct input, but when calling click(), nothing happens. Am I doing something wrong here ?

Thanks.

Edit: calling focus() on the input is working though.

Warven
  • 1
  • 1
  • 3
  • You might try calling `submit()` on a ref to the form, rather than calling `click()` on the submit button. https://www.w3schools.com/jsref/met_form_submit.asp – Chris Jul 24 '18 at 14:58
  • Well I already tried that but the behavior was weird too. the form resets itself and the function `this.handleSubmit` is never called, as if calling submit programatically squeezes out the `onSubmit` attribute :/ – Warven Jul 25 '18 at 09:34
  • Ok I got the correct way of calling the `onSubmit` function [here](https://github.com/facebook/react/issues/6796), the validation is still not triggered, but that's progress, I'll keep trying. – Warven Jul 25 '18 at 09:48
  • Ok well after much reading and hair pulling, I decided to use on submit validation instead of instant inline validation. I can't loose any more time on this. Plus, I stumbled upon [this article](http://uxmovement.com/forms/why-users-make-more-errors-with-instant-inline-validation/) that validates (hoho) my choice. – Warven Jul 25 '18 at 13:49

0 Answers0