Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

javascript - Easiest way to mask characters in HTML(5) text input

Does HTML5 have any kind of text field masking or do I still have to trap onkeydown etc.?

jbabey is right--"masking" as in blocking certain illegal characters, not hiding what's typed.

The best (as in simplest and most reliable) way I've found is to trap onkeyup and then just run a regex replace on the value of the textfield, removing any illegal characters.

This has a few advantages:

  1. It's easy to implement (one function, two lines of code).
  2. It's reliable and covers all cases I've thought of.
  3. It doesn't block key commands like copy/paste, select all or arrow keys.

But its major disadvantage is it shows the typed character(s) briefly before removing them, which makes it look very hackish and unprofessional.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Look up the new HTML5 Input Types. These instruct browsers to perform client-side filtering of data, but the implementation is incomplete across different browsers. The pattern attribute will do regex-style filtering, but, again, browsers don't fully (or at all) support it.

However, these won't block the input itself, it will simply prevent submitting the form with the invalid data. You'll still need to trap the onkeydown event to block key input before it displays on the screen.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...