简体   繁体   中英

Correct usage of email inputs in HTML5: Unexpected value of Input tag with email type in Chrome browser

In the following code, simple email validation is performed. The background of input is white for valid email and yellow for wrong values. It works fine in Firefox but in Chrome the background is white for values like " a@b.c ". It seems Chrome return trimmed value for this.value . Is this behavior normal and based on documents? Is bad usage of email input result in this behavior?

It will fix if text type is used instead of email. But I try to use HTML5 features.

 document.getElementById('userMail').onkeyup = function() { if(this.value.match(/^[a-z0-9]+@[a-z0-9]+\.[az]+$/i)) { this.style.background = "white"; } else { this.style.background = "yellow"; } }
 Email: <input type="email" id="userMail">

According to the standard , browsers should remove the beginning and ending spaces and line breaks - ie these characters are quite acceptable when typing.

At the same time, it may well be compatible with the support of the multiple attribute, which you can optionally enable at any time. Of course, the separators are cleared according to the standard.

Therefore, different browsers (and their versions,) there are several different approaches to the interpretation of the requirements of the standard. and naturally this behavior can change with any update.

For example, if you look at the example below, you will see that if you specify the value " a@b.c, a@b.c " then Chrome performs an additional full cleanup (Firefox only partial), but at the same time both Firefox and Chrome consider this field valid.

 const input = document.querySelector('input'); input.value = ' a@b.c, a@b.c '; input.oninput = function() { console.log(this.value); } console.log(input.value)
 input[type=email]:invalid { border: 1px solid red; }
 Email: <input type="email" required multiple value=" a@b.c, a@b.c ">

As a result, if you want a uniform solution, it is better to manually do additional cleaning and validation in this field on JS.

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