简体   繁体   English

写一个ng-pattern来禁止空格和特殊字符

[英]write an ng-pattern to disallow whitespaces and special characters

I am trying to get an angular ng-pattern to check that a username has no whitespaces or special characters. 我试图获得一个角度ng模式来检查用户名没有空格或特殊字符。 The following form return false if you enter whitespaces or special characters. 如果输入空格或特殊字符,则以下形式返回false。 However, it becomes true as soon as you enter az, Az or 0-9. 但是,只要输入az,Az或0-9,它就会变为真。 I have tried ng-pattern="/[^\\s]+/" and \\S and [^ ] but they make no difference. 我试过ng-pattern =“/ [^ \\ s] + /”和\\ S和[^],但它们没有区别。

<form name="myform">
  valid? {{ myform.$valid }}
  <input type="text" name="username" ng-model="username" ng-pattern="/[a-zA-Z0-9^ ]/" required/>
</form>

Here's the form in a plunk: http://plnkr.co/edit/6T78kyUgXYfNAwB4RHKQ?p=preview 这是插件中的表格: http ://plnkr.co/edit/6T78kyUgXYfNAwB4RHKQ? p = preview

Try the following pattern: 尝试以下模式:

/^[a-zA-Z0-9]*$/

This allows only alphanumeric characters. 这仅允许使用字母数字字符。

To surface the specific answer I was looking for, I already had the pattern suggested by Sniffer /^[a-zA-Z0-9]*$/ , but angular still appeared to ignore leading/trailing whitespace. 为了表达我正在寻找的具体答案,我已经有了Sniffer建议的模式/^[a-zA-Z0-9]*$/ ,但是角度似乎仍然忽略了前导/尾随空格。 As Cristian mentions in the comments: 正如克里斯蒂安在评论中提到的那样:

Angular will trim the input model, meaning that the validation doesn't trigger for spaces. Angular将修剪输入模型,这意味着验证不会触发空格。 You can add an ng-trim="false" to the input to fix this. 您可以在输入中添加ng-trim="false"来解决此问题。

Note that Angular is trying to protect you by silently trimming whitespace by default. 请注意,Angular会尝试通过默认情况下静默修剪空白来保护您。 In my case, I want the user to be aware that the trailing whitespace is invalid. 在我的情况下,我希望用户知道尾随空格是无效的。

in case anyone needs to disallow user entering emails in the address field 以防任何人需要禁止用户在地址栏中输入电子邮件

ng-pattern="/^[^@]+$/" NG-图案= “/ ^ [^ @] + $ /”

<div ng-messages="vm.updateCC.mailingAddress.$error" ng-show="vm.updateCC.mailingAddress.$touched">
     <p class="validation-message" ng-message="pattern">Please enter a valid address</p>
</div>

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

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