Home  >  Article  >  Web Front-end  >  Javascript uses regular expressions to control the values ​​allowed to be entered in the input input box_javascript skills

Javascript uses regular expressions to control the values ​​allowed to be entered in the input input box_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:43:471580browse

1、只允许输入数字

<input name="username" type="text" onkeyup="value=this.value.replace(/\D+/g,'')">

2、只允许输入英文字母、数字和下划线(以下二种方法实现)

<input name="username" type="text" style="ime-mode:disabled">
<input name="username" type="text" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')">

3、只允许输入英文字母、数字和=@#

<input name="username" type="text" onkeyup="value=value.replace(/[^\w=@#]|_/ig,'')">

4、只允许输入英文大写字母和数字

<input name="name" type="text" value="只录入大写字母和数字" style="color:gray" onfocus="this.value='';this.style.color='black'" onkeyup="this.value=this.value.replace(/[^A-Z0-9]/gi,'');this.value=this.value.toLocaleUpperCase();

5、只允许输入汉字

<input name="username" type="text" onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')">

【过滤文字输入】

TextField.restrict = "此处为可输入的内容";
field.restrict = "^此处为禁止输入的内容";

restrict属性支持一些类似正则表达式的样式:

field.restrict = "a-zA-z"; //只允许大小字母
field.restrict = "a-zA-z "; //只允许字母和空格
field.restrict = "0-9"; //只允许数字
field.restrict = "^abcdefg"; //除了小写字母abcdefg不允许外,其它都允许
field.restrict = "^a-z"; //所有小写字母都不允许,但是,其它内容都允许,包括大写字母
field.restrict = "0-9^5"; //只允许数字,但5例外

让restrict字符包含具有特殊意义的字母(例如-和^):

field.restrict = "0-9\\-"; //允许数字和破折号
field.restrict = "0-9\\^"; //允许数字和^
field.restrict = "0-9\\\\"; //允许数字和反斜杠

你也可以使用Unicode转义序列,指定允许的内容.例如:

field.restrict = "^\u001A";

注意:ActionScript有区分大小写的,如果restrict属性设为abc,允许字母的大写形式(A,B和C)输入时会变成小写对待形式(a,b和c),反之亦然.restrict属性只影响用户可以输入的内容,脚本可将任何文本放入文本字段中.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn