ASP 可选句号和字符限制字符需要验证表达式

ASP Validation Expression Required For an Optional full stop and characters with limits of character

ValidationExpression="^[a-zA-Z]*(\.{1}[a-zA-Z]*)?$" 

上面是我的验证表达式,对字符工作正常并接受"full-stop(.)",我只是想限制字符,尝试了很多但没有成功。

您现有的表达式不应该接受字符串 "full-stop(.)",因为它没有任何允许使用破折号 - 字符的指示符。

确保字符被正确转义

目前,您的括号字符未被转义,因为它们在正则表达式中 "special",您需要分别使用 \(\) 来转义。

ValidationExpression="^[a-zA-Z]*\(\.{1}[a-zA-Z]*\)?$"

将范围应用于字符集

如果您只想允许特定数量的特定字符,您可以将 * 替换为 {min,max} 以明确允许特定范围的值:

// This would allow between 1-4 letters, followed by an optional set of parentheses
// that contain a period and 1-4 letters (e.g. full(.test), lol(.jk), etc.)
ValidationExpression="^[a-zA-Z]{1,4}\(\.[a-zA-Z]{1,4}\)?$" 

允许附加字符

同样,如果你想允许不同的字符,你可以在你的字符集分组中定义它们 [...]。例如,如果您想允许包含破折号和字母,您可以使用 :

// The explicitly escaped "\-" within your character groups indicates that 
// you want to allow dashes within your strings
ValidationExpression="^[a-zA-Z\-]*\(\.[a-zA-Z\-]*\)?$" 

限制总字符串长度

您可以在正则表达式中附加如下所示的部分来处理限制表达式本身的总长度:

// The leading ^(?=.{min,max}$) section will define a constraint that the
// overall expression must be between min and max characters to be valid
ValidationExpression="^(?=.{min,max}$){your-expression-here}$"

因此,如果您想将表达式限制为总共只接受 8 到 12 个字符,您可以使用:

ValidationExpression="^(?=.{8,12}$)[a-zA-Z\-]*\(\.[a-zA-Z\-]*\)?$"