简体   繁体   English

如何使用ngPattern验证包含受限字符的输入?

[英]How to use ngPattern to validate an input containing restricted characters?

I try to validate the input of restricted characters. 我尝试验证受限字符的输入。 The input field only accept alphabet, dash and underscore characters. 输入字段仅接受字母,破折号和下划线字符。

When I test the code below, the first character is accepted, but the second one raise a pattern error. 当我测试下面的代码时,第一个字符被接受,但是第二个字符引发模式错误。

My RegEx: /^[a-zA-Z_-]$/ 我的RegEx: / ^ [a-zA-Z _-] $ /

HTML code: HTML代码:

<input ng-model="inputText" name="inputText" required md-maxlength="{{options.maxTextLength}}" md-autofocus ng-keypress="keypress($event)" ng-change="textChanged()" ng-pattern='/^[a-zA-Z_-]$/'>
<div ng-messages="inputTextForm.inputText.$error">
    <div ng-message="required">Input is required.</div>
    <div ng-message="md-maxlength">Input has reached the maximum characters allowed.</div>
    <div ng-message="pattern">Invalid characters.</div>
</div>

This code is in an Angular Material Dialog (v1.0.9) 该代码在“角度材质”对话框(v1.0.9)中

For more than one character you need the * at the end of the pattern, ie: 对于多个字符,您需要在模式末尾加* ,即:

<input ... ng-pattern="/^[a-zA-Z_-]*$/" />
<!--                               ^   -->
<!--                               |   -->
<!--             HERE -------------+   -->

See fiddle: https://jsfiddle.net/5wa5478c/ 参见小提琴: https//jsfiddle.net/5wa5478c/

With this, this regex indicates that valid input is the start of a line (^), followed by one of the approved characters, followed by the end of the line ($). 这样,此正则表达式表示有效输入是行的开头(^),后跟一个批准的字符之一,然后是行的末尾($)。

Remove ^ and $, and it should work! 删除^和$,它应该可以工作!

ng-pattern='/[a-zA-Z_-]/'

Test your code here first: http://rubular.com/ 首先在这里测试您的代码: http : //rubular.com/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM