Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine RegularExpressionValidator control and RequiredFieldValidator?

I often use regex expression validators that are also a required field. Which leads to what seems like redundant controls on the page. There is no "Required" property of the regex validator which means I need another control. Like this:

<asp:TextBox ID="tbCreditCardNumber" runat="server" Width="200"></asp:TextBox>
<asp:RegularExpressionValidator ID="revCreditCardNumber" runat="server"
        ControlToValidate="tbCreditCardNumber" ValidationGroup="CheckoutGroup" ErrorMessage="Invalid Credit Card Number!"
        ValidationExpression="^(3[47][0-9]{13}|5[1-5][0-9]{14}|4[0-9]{12}(?:[0-9]{3})?)$">*</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="rfvCreditCardNumber" runat='server' ControlToValidate="tbCreditCardNumber" ValidationGroup="CheckoutGroup"
        ErrorMessage="Credit Card Number Required">*</asp:RequiredFieldValidator>

Is there a way to combine the two controls so I don't have to type so much code?

like image 359
Dan Bailiff Avatar asked Dec 17 '22 07:12

Dan Bailiff


2 Answers

One common problem is that the validator component still takes space when it is not shown, which looks odd if you have several and i.e. the last one is triggered leaving a larger gap to the asterisk or other error marker. This can be easily solved by adding:

display="Dynamic"

...to the validator.

But it does not solve the problem of several trigging at the same time which will still show many validator errors in a row. A custom validator would then probably be the best solution.

like image 125
Johncl Avatar answered Jan 25 '23 23:01

Johncl


You can roll your own CustomValidator, combining the functionality. Other than that, no not to my knowledge.

like image 37
Ian Jacobs Avatar answered Jan 26 '23 00:01

Ian Jacobs