0

I have a simple form and the problem is that the validation happens after the click event is registered, thus triggering the doSomething() function. I would like the email validation to stop the user from submitting the form so that the function will not be triggered. How would I do that?

<form>
  <input type="email" placeholder="your email here" required/>
  <button type="submit" onClick="doSomething()">Submit</button>
</form>

<script>
function doSomething(){
    // gets triggered even when the email does not pass validation
    console.log('Doing work..');
}
</script>

JSFiddle

Alexandru Antochi
  • 1,295
  • 3
  • 18
  • 42

1 Answers1

3

You could use the onSubmit attribute in the form, which will only call your function when all fields are validated.

<form onSubmit="doSomething()">
  <input type="email" placeholder="your email here" required/>
  <input type="submit"/>
</form>

<script>
function doSomething(){
    // gets triggered even when the email does not pass validation
    console.log('Doing work..');
}
</script>

View this question to understand how to stop the form from submitting.

Thanks,

Jack Dane
  • 402
  • 3
  • 12