简体   繁体   中英

Set custom error message when using pattern attribute in HTML5 not working in IE 11

I have the following HTML code:

<form role="search" id="searchform" action="/search" method="get">
      <input value="" name="query" type="search" placeholder="" required="" pattern="^[a-zA-Z_0-9\s]+$">
      <button type="submit"><i class="ion ion-ios-search"></i></button>
</form>

and Javascript code:

document.getElementsByName("query")[0].oninvalid = function (ev) {
  ev.preventDefault();
  ev.target.setCustomValidity( 'Only numbers, letters and space are allowed !' );
}

Seems that work only in Firefox, Chrome and Safari but not in Internet Explorer 11.

Not working mean that appear standard message like: You must use this format:

What I missed ?

When you use pattern check, the error message is defined in the title attr. Change for :

<input value="" name="query" type="search" placeholder="" required="" pattern="^[a-zA-Z_0-9\s]+$" title="Only numbers, letters and space are allowed !">

and remove your JS

As taken form this answer , constraint validation messages do work in IE11 with:

element.setCustomValidity("error message") .

Done inline using the oninvalid attribute:

<form role="search" id="searchform" action="/search" method="get">
  <input value="" 
         name="query" 
         type="search" 
         placeholder="" 
         required="" 
         pattern="^[a-zA-Z_0-9\s]+$"
         oninvalid="setCustomValidity('Only numbers, letters and space are allowed!')" 
         oninput="setCustomValidity('')">
  <button type="submit"><i class="ion ion-ios-search"></i></button>
</form>

Also, might want to clear the message oninput :

oninput="setCustomValidity('')"

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