Michael McCarthy
Michael McCarthy

Reputation: 1542

How to disallow a period in an MVC TextBox using the RegularExpression attribute

I have a current requirement where I need to make sure a user is not putting a period (".") in a textbox using MVC4.

So, this should be allowed: 30
But this should be disallowed: 30.2

I am trying to use the RegularExpression attribute, but I can't find a combination that works:

public class StudyRandomizationCap
{
    [Range(1, 100, ErrorMessage = "Milestone must be between 1 and 100.")]
    [RegularExpression(@"\.", ErrorMessage = "Milestone percentage values cannot contain decimals.")]
    public short? MilestonePercentage1 { get; set; }
}

This fails validation on the client side for any number I enter, regardless of whether or not there is a decimal in it or not.

Changing it to this:
[RegularExpression(@"[^.]", ErrorMessage = "Milestone percentage values cannot contain decimals.")]

Will allow a single number between 1-9, but the minute the number is 10 and above it fails. Again, this is all on the client side.

Why is it failing on numbers between 1-100 depending on which regular expression I'm using? It there a better/easier way to do this than using regular expressions? Is there some type of limitation on how Javascript executes regular expressions that would be different from the ModelBinder?

This seems like a fairly simple and trivial check, and to me, the regular expression check should only be failing if there is a "." in the textbox.

Upvotes: 0

Views: 567

Answers (1)

David Esteves
David Esteves

Reputation: 1604

Your regex is only matching a single character, you need to tell it to be able to match more, something like:

[RegularExpression(@"[^\.]+", ErrorMessage = "Milestone percentage values cannot contain decimals.")]

The + will mean it has to be 1 or more characters long. What you should do if you only want numbers though is to have something like

[RegularExpression(@"[0-9]+", ErrorMessage = "Milestone percentage values cannot contain decimals.")]

Your initial query will prevent them from entering a . but they can still input other characters such as symbols or A-z

Upvotes: 1

Related Questions