Michael McCarthy
Michael McCarthy

Reputation: 1542

RangeAttribute validator not validating on whole numbers correctly in MVC4 on the client side

I have the following RangeAttribute validator on one of my model's properties:

[Range(1, 100, ErrorMessage = "Milestone must be between 1 and 100.")]
public int? MilestonePercentage1 { get; set; }

Currently, the validator works to flag a decimal value of ".2" being input into the textbox. It also flags a value of "0.2"...

BUT, the minute I set the number to the left of the decimal to one or greater:

"1.0" or "1.2", etc... the validator thinks that this is ok, and does not flag it.

I'm specifiing int in model, so I don't know whey ".2", or "0.9" are considered invalid, and "1.2" is considered valid.

I have written a test for the attribute off the model using NUnit and it runs correctly (.GetAttributesOn is an extension method we wrote):

private RangeAttribute rangeAttribute;

[SetUp]
public void Given()
{
    rangeAttribute = new StudyRandomizationCap()
                .GetAttributesOn(s => s.MilestonePercentage1)
                .OfType<RangeAttribute>()
                .Single();
}

[TestAttribute]
public void DoesNotAllowAValueThatContainsADecimal()
{
    Assert.That(rangeAttribute.IsValid("3.2"), Is.False);
}

but the minute I have to rely on the javascript used by the validator on the client side, the value "3.2" is considered valid.

I"m thinking something is lost in translation for this validator when using the client side script (which I believe is jquery.validate.js?)

Any ideas?

Upvotes: 0

Views: 173

Answers (1)

Floremin
Floremin

Reputation: 4089

Try this:

[Range(typeof(int), 1, 100, ErrorMessage = "Milestone must be between 1 and 100.")]
public int? MilestonePercentage1 { get; set; }

Upvotes: 1

Related Questions