Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite default browser form validation

Suppose you have an input for email like this:

<input type='email' placeholder='Email:' required />

In Chrome and other modern browsers having type set to email enables validation i.e. only email like "something@something" will be valid. It displays default popup message like this:

enter image description here

I was wondering if it is possible to tap into these events in order to use them for a custom validation? And disable default browser ones.

like image 303
Ilja Avatar asked Oct 24 '25 14:10

Ilja


2 Answers

First you need to disable default browser validation. To do so, just add novalidate to form element:

<form class="custom-validated-form" novalidate >
    <input type='email' placeholder='Email:' required />
</form>

To do some custom validation you need to catch the submit event and do .preventDefault() in case your custom validation failed:

$('.custom-validated-form').submit(function(event) {

    // your custom validation

    event.preventDefault()
})

Good idea might be to use third-party library such as parsley.js to handle the validation for you.

like image 77
Martin Gottweis Avatar answered Oct 27 '25 03:10

Martin Gottweis


You can disable client-side HTML5 browser validation by adding the novalidate flag to your form tag:

<!-- This validates as normal -->
<form method="post" action="#">
  <input type="email" placeholder="Validate Email:" required />
  <input type="submit">
</form>

<!-- This adds the `novalidate` flag -->
<form method="post" action="#" novalidate>
  <input type="email" placeholder="Novalidate Email:" required />
  <input type="submit">
</form>

This will allow you to still use HTML input types (such as "email") and prevent the browser from running validations.

From that point, you would be open to implementing your own solution, or integrating one of many third-party validation plugins (such as jQuery Validation).


Furthermore, if you would like to keep the HTML5 validation, but alter the validation message, you can use setCustomValidity -- It may present some browser difficulties, but it's a viable option none the less.

like image 40
Wes Foster Avatar answered Oct 27 '25 03:10

Wes Foster