Skip to content

Instantly share code, notes, and snippets.

@yangg
Created April 24, 2012 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yangg/2476043 to your computer and use it in GitHub Desktop.
Save yangg/2476043 to your computer and use it in GitHub Desktop.
Filter User Input by Regex
<!-- tested on chrome & ie9 -->
<input type="text" pattern="\d+" onkeypress="return keyFilter()" />
<input type="text" pattern="\d{11}" maxlength="11" onkeypress="return keyFilter('\\d')" />
<script>
/**
* 限制input的可输入字符类型(不包含长度)
*/
function keyFilter(opt_pat) {
var e = arguments.callee.caller.arguments[0] || window.event,
pattern = opt_pat || (e.target || e.srcElement).getAttribute("pattern");
return new RegExp(pattern).test(String.fromCharCode(e.keyCode));
}
// PS: chrome doesn't support ime-mode:disabled
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment