Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
324 views
Welcome To Ask or Share your Answers For Others

1 Answer

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,


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...