我想对名称进行验证,强制用户在四个部分(四个名字)中输入他的名字。如何在客户端使用asp.net验证?
<td style="text-align: right;" class="style1">
<asp:TextBox ID="txt_addName" runat="server" Width="220px" ValidationGroup="add"></asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txt_addName_TextBoxWatermarkExtender"
runat="server" Enabled="True" TargetControlID="txt_addName"
WatermarkText="أدخل اسم المحاضر رباعيا" WatermarkCssClass="watermark">
</cc1:TextBoxWatermarkExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="txt_addName" Display="Dynamic" ErrorMessage="!"
ValidationGroup="add"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ErrorMessage="*"
ValidationExpression="^(?:\p{L}+\s+){3}\p{L}+$" ControlToValidate="txt_addName"
Display="Dynamic" ValidationGroup="add">يجب أن يكون اسم المحاضر رباعيا
</asp:RegularExpressionValidator>
</td>
<td style="text-align: center; width: 550px;">
<asp:Button ID="btn_addNewLecterer" runat="server" Font-Bold="True" Font-Names="Garamond"
Font-Size="Medium" Text="أضف محاضر جديد" OnClick="btn_addNewLecterer_Click" ValidationGroup="add" />
</td>
答案 0 :(得分:5)
这样的事情应该有效:
^(?:\p{L}+\s+){3,}\p{L}+\s*$
说明:
^ // start at the beginning of the string
(?: // start a non-capturing group
\p{L} // match any unicode letter...
+ // ...at least one of them...
\s+ // ...followed by at least one white-space character
) // end the non-capturing group
{3,} // repeat the group at least three times
\p{L}+ // finish with at least one unicode character...
\s* // ...that can optionally be followed by white-space...
$ // ...and then the string should end
如果要将表达式限制为要求完全四个部分(我将问题解释为要求至少四个),则将其更改为:
^(?:\p{L}+\s+){3}\p{L}+$
答案 1 :(得分:2)
你会想要这样的东西:
^\w+\s\w+\s\w+\s\w+$
您希望使用+
代替*
,因为您确实至少想要其中一个。
使用\w
,因为您希望捕获所有字词 - 而不仅仅是字母a-z
您也可以使用文字空格而不是\s
类,只要您没有明确指定您希望模式忽略空格,那么:
^\w+ \w+ \w+ \w+$
\s
将允许制表符和空格。
正如Frederik所说,只要你启用了验证控件的客户端验证,这样一个简单的正则表达式也可以在客户端工作。
答案 2 :(得分:1)
您可以尝试像Regex Buddy这样的正则表达式创建程序来创建自己的规则。 这是一个简单的,只允许四个名称部分(所有小写字母)用空格分隔
^[a-z]*\s[a-z]*\s[a-z]*\s[a-z]*$
您可以改进并将其作为基础使用。