Regular Expression Validator does not validate empty textbox

TTCG picture TTCG · Jun 30, 2010 · Viewed 27.6k times · Source

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>

Answer

Kelsey picture Kelsey · Jun 30, 2010

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.