简体   繁体   中英

Override html5 validation

I'm working on a simple login form, with two fields:

<form>
  <input type="email" name="email" required />
  <input type="password" name="password" required />
  <button type="submit">Log in</button>
</form>

For modern browsers, validation is automatically triggered.

However, if javascript is available, I want to take over the html5 form validation, and handle everything myself.

I want to validate automatically 'onblur' (only the affected field) and I want to validate all fields when 'submit' is clicked.

The onblur events work fine, however.. When 'submit' is pressed, the standard 'submit' event is not triggered. However, an 'invalid' event is triggered; but only for the first invalid event.

What's a nice way to tell the browser to ignore all HTML5-related validation, and take over the entire process?

Please be advised that — even though some browsers may support the attribute novalidate on INPUT elements — the HTML code does not validate.

According to documentation there is no such attribute. Only the FORM element may contain the novalidate attribute.

This answer is incorrect. Please see willydee's answer.

Simple, just add the novalidate property to any element you don't want the browser to validate, like so:

 <form> <input type="email" name="email" required novalidate /> <input type="password" name="password" required /> <button type="submit">Log in</button> </form> 

Since you wish to only cancel validation when JavaScript is available, add it with JavaScript (using jQuery for simplified example)

 $('input[novalidate]').attr('novalidate', 'novalidate'); 

如果您使用jQuery的另一个选项是删除该属性。

$("input[required],select[required],textarea[required]").removeAttr('required');

也许您可以使用javascript将所有“必需”属性转换为“需要数据”,因为您可以使用javascript处理它们并使用您自己的处理程序覆盖html5表单验证

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM