Why this code allows user do not enter any text? AFAIK +
means One or more
.
<asp:TextBox ID="myTextBox" runat="server" MaxLength="9" />
<asp:RegularExpressionValidator runat="server"
ControlT开发者_开发技巧oValidate="myTextBox"
ValidationExpression="\d+"
ErrorMessage="Error!" />
I want user was able to enter only 9 digits. And this field is required. How can I do that?
From MSDN:
Note: Validation succeeds if the input control is empty. If a value is required for the associated input control, use a RequiredFieldValidator control in addition to the RegularExpressionValidator control.
The regex validators only work when text is entered by default. I would recommend putting in a separate RequiredFieldValidator so you can have a more helpful error message.
Now your ValidationExpression should be \d{9}
.
Most asp.net validators do not fire when there is no text. This basically introduces the need for an extra RequiredFieldValidator
, which you should add:
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
ControlToValidate="myTextBox"
Display="Static"
ErrorMessage="Required field"
runat="server"/>
Can you post the rest of the code from the page, this bit looks good but the problem might lie within the form you are using, do you have runat="server" in your form declaration?
Try adding this:
<asp:RequiredFieldValidator ID="rfv" Display="None" runat="server" ControlToValidate="myTextBox" ErrorMessage="name is required!"></asp:RequiredFieldValidator>
精彩评论