Johnrad
Johnrad

Reputation: 2655

ASP.NET - Regular Expression Validator

I need a regular expression that only excepts numbers divisible by 1.5. I have no idea if this is even possible?

I checked regex library and they have nothing on it. Any one have any ideas?

Upvotes: 0

Views: 1486

Answers (3)

It is not a good idea to use regular expressions to validate numerical values. Better to write a small validator function just for this purpose.

You could validate numeric/non-numeric very easily with this regex: [0-9]+ Of course this will allow many leading zeros and does not take decimals into account. You can get more sophisticated, such as [0-9]+(\.(0|[0-9]+))? I think this would make the decimal optional. And we haven't even started into negative signs, scientific notation, and other notation formats. If you specify the allowed input format, we can help much more easily with a regex.

Upvotes: 1

Greg
Greg

Reputation: 16680

As others have said, Regex is not the right tool and it's better to use a CustomValidator like the following:

<asp:CustomValidator ID="DivisibleByOnePointFiveValidator" runat="server" ErrorMessage="Must be divisible by 1.5!"
    Display="Dynamic" ControlToValidate="MyTextBox" EnableClientScript="false" 
    OnServerValidate="DivisibleByOnePointFiveValidator_ServerValidate" >
</asp:CustomValidator>

    protected void DivisibleByOnePointFiveValidator_ServerValidate(object source, ServerValidateEventArgs args)
    {
        decimal inputValue;
        if (!decimal.TryParse(args.Value, out inputValue))
        {
            args.IsValid = false;
            return;
        }

        args.IsValid = inputValue % 1.5M == 0;
    }

Upvotes: 3

Keith
Keith

Reputation: 5391

Regular expressions are meant for string validation, not numeric validation (other than saying whether something is or is not numeric). You're going to need a custom validator for this.

Upvotes: 2

Related Questions