tags:

views:

32

answers:

4

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"
   ControlToValidate="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?

+1  A: 

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"/> 
klausbyskov
+1  A: 

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}.

Min
Why don't you recommend using that property? What is it's name?
abatishchev
Woops my fault. I was mistaken. I'll edit my response. I still wouldn't recommend it if it exists because the error message is less useful. Error in my experience work better when they are very clear and specific.
Min
A: 

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>
Kaius
+3  A: 

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.

AakashM