0

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?

3 Answers 3

3

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

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: 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...).
Actually not my question, was expanding on Keith's answer. Which I should have specified!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.