简体   繁体   English

ASP.Net:RegularExpressionValidator ValidationExpression一次防止`;`和`-`

[英]ASP.Net: RegularExpressionValidator ValidationExpression to prevent `;` and `–` at a time

I want to make an ASP.Net RegularExpressionValidator ValidationExpression that will prevent to give input ; 我想制作一个ASP.Net RegularExpressionValidator ValidationExpression ,它将阻止输入; and –- . –-

I can do it for and it is ValidationExpression="[^-]*" . 我可以这样做它是ValidationExpression="[^-]*"

<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
      runat="server" 
      ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="**" 
      ValidationExpression="[^-]*"></asp:RegularExpressionValidator>

Above expression can prevent single character. 上述表达式可以防止单个字符。 I will give permission for single character. 我将给予单个许可字符。 I will block for double characters ( -- ). 我会阻止双字符( -- I need to prevent ; 我需要预防; and at a time. 而且一次。

Can anyone help me? 谁能帮我?

The Regex needs to get smarter. 正则表达式需要变得更聪明。 You want to block multiple hyphens, the m-dash, and semicolons. 您想要阻止多个连字符,m-dash和分号。

So, try @"^(?=[^–;]*)((?!--).)*$" 所以,试试@"^(?=[^–;]*)((?!--).)*$"

Breaking it down: 打破它:

The ^ matches the start of a line, and helps ensure that the validator is used to match the entire string. ^匹配行的开头,并帮助确保验证器用于匹配整个字符串。

The expression in the first set of parentheses will match any set of characters that do not include the m-dash and semicolon. 第一组括号中的表达式将匹配不包含m-dash和分号的任何字符集。 You may want to substitute the hex value for the m-dash using the \\x2014 escape sequence. 您可能希望使用\\x2014转义序列替换m-dash的十六进制值。 It is defined as non-consuming with the ?= , meaning the Regex engine must match this pattern but will not advance its index when it finds the match, so the same set of characters will be tested for the next pattern as well. 它被定义为非消耗的?= ,意味着正则表达式引擎必须匹配此模式,但在找到匹配时不会推进其索引,因此同样的字符集也将针对下一个模式进行测试。

The expression in the second set of parentheses is an inverse look-ahead; 第二组括号中的表达式是反向前瞻; it will match any set of characters not containing two (or more) adjacent hyphens. 它将匹配任何不包含两个(或更多)相邻连字符的字符集。 This may be a bit slow, however; 然而,这可能有点慢; this regex basically forces the Regex engine to consider each character one at a time, looking ahead from that point to ensure the next character won't make match the inverse pattern. 这个正则表达式基本上迫使正则表达式引擎一次考虑一个字符,从那一点向前看,以确保下一个字符不会与反向模式匹配。

The trailing $ marks the end of a line; 尾随$标志着一条线的终点; together with the ^ it ensures that you are looking at everything in a single string (or line in multiline data) when determining a match. ^一起确保您在确定匹配时查看单个字符串(或多行数据中的行)中的所有内容。

Plug this into a Regex tester like Derek Slater's and play around with it to make sure it will stop all the scenarios you want. 将其插入Derek Slater's等Regex测试仪中,并使用它来确保它能够停止您想要的所有场景。

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

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