admin管理员组

文章数量:1418861

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:

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.

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:

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.

Share Improve this question asked Jun 2, 2016 at 14:18 IljaIlja 46.6k103 gold badges289 silver badges528 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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.

本文标签: javascriptOverwrite default browser form validationStack Overflow