I have the following regex set as the ValidationExpression property on a RegularExpressionValidator in a web form. When I enter an illegal character in the validated control, the validator detects it and shows an error message.
<appSettings>
<add key="categoryPattern" value="^[a-zA-Z0-9_+\-() ]{1,50}$" />
</appSettings>
My validator:
<asp:RegularExpressionValidator ValidationExpression="<%$ AppSettings:categoryPattern %>"
My server side validation:
Regex rex = new Regex(ConfigurationManager.AppSettings["categoryPattern"]);
if (!rex.Match(categoryName).Success)
{
throw new ArgumentException("CategoryName must match expression: " + rex);
As you can see, exactly the same pattern is applied client side and server side.
However, when I clear the validated control and submit an empty string, the validator thinks it’s OK, and I get an error from my server side validation. Anyone know what is wrong here, except for the broken contract of the RegularExpressionValidator?
It is by design. You should also add a
RequiredFieldValidatorto force user entry.RegularExpressionValidatorassumes empty fields as valid (and doesn’t even run them throughRegex). The reason behind this is that for instance, you might have an optionalEmail address 2field in the form that is not required, but if it’s entered, it should be a valid email address. To achieve this easily, other validators ignore empty fields and if you need to make them required, you’d just add anotherRequiredFieldValidator.In fact, it’s not necessary to manually revalidate on server. ASP.NET validators also support server-side validation built it. You could just check
Page.IsValidproperty.