开发者

Regular Expression Validator does not validate empty textbox

I would like to validate the textbox for specific text and it must not be blank. But the regular expression validator is not v开发者_运维技巧alidating 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>


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜