繁体   English   中英

ASP.NET MultiLine TextBox - 带有NewLine的MaxLength的RegularExpressionValidator(\\ r \\ n) - 客户端和服务器端验证的差异

[英]ASP.NET MultiLine TextBox - RegularExpressionValidator for MaxLength with NewLine (\r\n) - Difference in Client & Server Side Validation

背景:我正在开发一个ASP.NET网页,我有一个多行文本框,如下所示

<asp:TextBox ID="textBox1" runat="server" TextMode="MultiLine"></asp:TextBox>

和一个正则表达式验证器来检查最大长度,如下所示

<asp:RegularExpressionValidator ID="validator1" runat="server" ControlToValidate="textBox1" ValidationExpression="^[\s\S]{0,10}$" ErrorMessage="You can only enter a maximum of 10 characters"></asp:RegularExpressionValidator>

我们的想法是将用户输入限制为最多10个字符。 您可能知道, RegularExpressionValidator同时进行客户端和服务器端验证。

问题:对于具有换行符的用户输入,客户端字符数似乎小于服务器端字符数。 因此,它通过了客户端验证,但在服务器端验证失败。

这可能是因为在客户端,新行字符是\\n而在服务器端它是\\r\\n

不知道如何解决这个问题? 请注意我需要客户端和服务器端验证。

测试数据:

Line
Line1

更新:除了上述奇怪之外,还有更多的方式\\r\\n由.Net处理

  1. 如果包含\\r\\n的文本通过.Net web service传递,则会自动序列化为\\n 因此,在web service调用之前和之后,包含\\r\\n的字符串的计数/长度会有所不同。

  2. 如果包含\\r\\n的相同文本存储在SQL Server则它将保留原样\\r\\n

因此,根据MultiLine TextBox的值如何进一步处理,验证逻辑需要更改。 在我的例子中, string在到达外部系统之前通过web service传递 - 因此@sln建议的regexclient and server side validation上都能很好地工作。

但是,如果要将值直接存储在SQL Server并希望使用regex验证stringregex其他步骤,例如在从数据库读取和显示时将\\r\\n替换为\\n ,反之亦然。

也许,验证最大长度字符的整个方法是XY问题的一个案例,其中可能有一个更优雅的方式来做到这一点?

您可以使用它在两侧运行^(?:\\S|[^\\S\\r\\n]|\\r?\\n){0,10}$

 ^ 
 (?:
      \S              # Not whitespace
   |  [^\S\r\n]       # or, whitespace, not CR or LF
   |  \r? \n          # or, CR(optional)LF
 ){0,10}
 $

仅限换行符 -

 **  Grp 0 -  ( pos 0 , len 10 ) 
Line
Line1

CRLF

 **  Grp 0 -  ( pos 0 , len 11 ) 
Line
Line1

更新:
CRLF翻译助手

我发现这些惯例是地球上最快的。
它们是单通道正则表达式,可以瞬间完成巨大的兆字节转换。
这个伪代码是C ++范例。

// To Normalize to CRLF 
// -------------------------
// regex  CRLFCRtoCRLF( "(?>\\r\\n?)|\\n" ); // Dot-Net style
regex  CRLFCRtoCRLF( "\\r\\n?+|\\n" ); // Pcre/Perl style

void ReplaceCRLFCRtoCRLF( string& strSrc, string& strDest )
{
    string repl = "\\r\\n";
    strDest = regex_replace( strSrc, CRLFCRtoCRLF, repl );
}


// To Normalize to LF 
// -------------------------
regex  CRLFCRtoLF( "\\r\\n|\\r(?!\\n)" );

void ReplaceCRLFCRtoLF( string& strSrc, string& strDest )
{
    string repl = "\\n";
    strDest = regex_replace( strSrc, CRLFCRtoLF, repl );
}


// To find current state (not really needed)
// (Returns true if standalone CR or LF)
// ------------------------------------------
regex  CRorLF( "\\A(?>[^\\r\\n]*)(?>(?:\\r\\n)+[^\\r\\n]*)*\\z" );

bool IsLoneCRorLF( string& strSrc )
{
    // In this case we are going to try to match an entire
    // string that is free of lone cr's or lf's.
    // Then return the negative of that.
    // This is much faster than using the lookround's,
    // and we need a little speed here.
    return !regex_search( strSrc, CRorLF );
}

暂无
暂无

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

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