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?

share|improve this question

feedback

3 Answers

up vote 3 down vote accepted

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;
    }
share|improve this answer
feedback

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.

share|improve this answer
feedback

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.

share|improve this answer
To expand.. the RE should validate whether the input is a number and another step should validate whether it is divisible by 1.5, so it will be a two step process. – DerekH Jan 4 '11 at 21:03
@DerekH: it would be a good idea to update your question to say you want to validate that the input is a numeric string within certain allowed formats (with/out decimals, leading zeros, scientific notation, etc...). – FrustratedWithFormsDesigner Jan 4 '11 at 21:11
Actually not my question, was expanding on Keith's answer. Which I should have specified! – DerekH Jan 4 '11 at 22:33
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.