简体   繁体   English

ng-pattern允许使用字母和某些特殊字符

[英]ng-pattern to allow alpha and certain special characters

In form - name field I want to do a validation against 在表单-名称字段中,我要针对

  • Should allow only Alpha characters 应该只允许使用Alpha字符
  • Allow space 留出空间
  • Allow certain special characters - _ \\ / - . ' 允许使用某些特殊字符_ \\ / - . ' _ \\ / - . '

I tried, 我试过了,

 ng-pattern="/^[a-z]+[_+\+/+-+.+’][a-z]*$/"

Looks like I have missed out something as its not working! 好像我错过了一些东西,因为它不起作用!

Let's see: 让我们来看看:

  • Should allow only Alpha characters => [a-zA-Z] 应该只允许Alpha字符 => [a-zA-Z]
  • Allow space => [ ] or \\s 允许空间 => [ ]\\s
  • Allow certain special characters - _ \\ / - . ' ' 允许使用某些特殊字符_ \\ / - . ' ' _ \\ / - . ' ' => [_\\\\\\/.''-] _ \\ / - . ' ' => [_\\\\\\/.''-]

So, combining all that, the pattern will look like: 因此,结合所有这些,模式将如下所示:

ng-pattern="/^[a-zA-Z _\\\/.’'-]+$/"

This matches 1 or more ( + ) chars from the allowed set. 这会匹配允许集中的1个或更多( + )字符。

To disallow leading/trailing whitespace, use 要禁止前导/尾随空格,请使用

ng-pattern="/^[a-zA-Z_\\\/.’'-]+(?: +[A-Za-z_\\\/.’'-]+)*$/" ng-trim="false"

See the regex demo 正则表达式演示

The ng-trim="false" will prevent from trimming the input sent to the regex engine. ng-trim="false"将阻止修剪发送到正则表达式引擎的输入。 The new regex will match: 新的正则表达式将匹配:

  • ^ - start of string ^ -字符串的开头
  • [a-zA-Z_\\\\\\/.''-]+ - 1 or more letters or allowed symbols other than space [a-zA-Z_\\\\\\/.''-]+ -1个或多个字母或除空格以外的允许符号
  • (?: +[A-Za-z_\\\\\\/.''-]+)* - zero or more sequences of: (?: +[A-Za-z_\\\\\\/.''-]+)* -零个或多个序列:
    • + - (or, \\s+ ) - 1 or more spaces (whitespaces) + -(或\\s+ )-1个或多个空格(空格)
    • [A-Za-z_\\\\\\/.''-]+ - see above [A-Za-z_\\\\\\/.''-]+ -参见上文
  • $ - end of string. $ -字符串结尾。

/^([az _\\/.'-])+$/i would do. /^([az _\\/.'-])+$/i可以。 If you want any space character instead of just space, use /(^[a-z_\\/.'-]|\\s)+$/i . 如果要使用空格字符而不是空格,请使用/(^[a-z_\\/.'-]|\\s)+$/i

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

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