ccook
ccook

Reputation: 5959

ASP.NET RegularExpressionValidator, validate on a non-match?

Is there a way to use the RegularExpressionValidator to validate only when the ValidationExpression does not match? In particular use a PO BOX regex to validate an address that is NOT a PO BOX.

Thanks!

Upvotes: 2

Views: 2578

Answers (5)

yonexbat
yonexbat

Reputation: 3012

Another solution for client side scripting:

<asp:TextBox runat="server" ID="MYiD" />


<asp:CustomValidator runat="server" ControlToValidate="MyId" ErrorMessage="Wrong"
    ClientValidationFunction="ClientValidate" />



<asp:Button runat="server" OnClick="OnClick" />

<script language="javascript"> 
function ClientValidate(source, arguments)
{
    var value = arguments.Value;
    var res = value.match('abc');       
    arguments.IsValid = (res == null || res === undefined);
}
</script>

Upvotes: 0

Nick Higgs
Nick Higgs

Reputation: 1702

You can effectively invert your regular expression using a negative look-ahead.

For example, consider the following regular expression that matches only a string of digits:

^\d+$

This expression could be inverted as follows:

^(?!\d+$).*$

Upvotes: 3

Canavar
Canavar

Reputation: 48088

Mike Chaliy's solution is very good, but it doesn't validate in client-side.

I think you should use a custom validator control and write a javascript function that validates not a POBox. copy pattern from regular expression validator and use this site to write your own client side validation.

Upvotes: 1

Mike Chaliy
Mike Chaliy

Reputation: 26658

Just use NegativeRegularExpressionValidator :)

[ToolboxData("<{0}:NegativeRegularExpressionValidator runat=\"server\" ErrorMessage=\"NegativeRegularExpressionValidator\"></{0}:NegativeRegularExpressionValidator>")]
public class NegativeRegularExpressionValidator : RegularExpressionValidator
{
    protected override bool EvaluateIsValid()
    {
        return base.EvaluateIsValid() == false;
    }
}

Upvotes: 3

Alex Reitbort
Alex Reitbort

Reputation: 13696

Create a regular expression that validates NOT a PO BOX or use custom validator.

Upvotes: 1

Related Questions