views:

52

answers:

3

I would like to validate the textbox for specific text and it must not be blank. But the regular expression validator is not validating if the text box is BLANK. However, it validates if I type something in the text box.

How can I make regular expression to trigger even if the text box is empty?

Should I use Required Validator + Regex Validator at the same time? Thanks.

<asp:TextBox ID="txtcard" runat="server" MaxLength="16"></asp:TextBox>

<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" 
ControlToValidate="txtcard" ErrorMessage="Please type credit card no" 
ValidationExpression="^\d{16}$"></asp:RegularExpressionValidator>
+3  A: 

You should use both at the same time. Not returning a Validation error if the Value is blank is common with the ASP.NET validation controls. You will see the same behavior from the Validation attributes in the System.ComponentModel.DataAnnotations namespace.

Yuriy Faktorovich
+1. You can get around this with a custom DataAnnotationValidator. I wrote one, but it requires inheriting from a base object. It's very useful: http://bit.ly/bcwher It allows you to add any number of ValidationAttributes to properties and displays the first error message that causes validation to fail (as multiple asp validators would)
Jim Schubert
A: 

I would generally do as you suggest and have a required validator as well. This would allow you to have a different message for each rule.

Another option that I would recommend any web developer look at is the JQuery validation plugin. If you combine this with Fluent Validation, you can keep all of your validation rules for your business objects in one place and you can validate on the Client side and at the Server using those same rules.

JQuery Validation

Fluent Validation

Daniel Dyson
A: 

You should combine your RegularExpressionValidator with a RequiredFieldValidator.

If either fails it will block due to validation firing. Each one serves a purpose and the RegularExpressionValidator's purpose is to validate entered text not the lack of text.

If you want to do it all in one validator your could use the CustomValidator and set ValidateEmptyText='true'. Then you could use the javascript regex to do the checking. I would recommend the two validators though as this is a standard approach.

Kelsey