There are three fields in my mvc3 page:rate, minrate and maxrate. Rate should be higher than minrate and less than maxrate. How can I achieve this with mvc3 model validation? This is the model:
[Required(ErrorMessage = "Rate Required")]
[Range(1, 9999999.999, ErrorMessage = "Invalid Rate")]
public decimal rate
{
get;
set;
}
/// <summary>
//min Rate
/// </summary>
[Required(ErrorMessage = "Min.Rate Required")]
[Range(1, 9999999.999, ErrorMessage = "Invalid Rate")]
public decimal minRate
{
get;
set;
}
/// <summary>
//max Rate
/// </summary>
[Required(ErrorMessage = "Max.Rate Required")]
[Range(1, 9999999.999, ErrorMessage = "Invalid Rate")]
public decimal maxRate
{
get;
set;
}
EDIT:
I tried performing the comparison on the client side with javascript. If I can find a way to dynamically change the validation message (eg: 'Max. Rate required' in the case of maxrate field) I could solve the problem. Is there any way to do that?
I tried this: (Some code omitted)
//...........................
$('#Save').click(function(){
if (parseFloat(maxrate) < parseFloat(rate)) {
$('#maxRateforvalidation').text("Rate must be less than maxrate");
//It works but the styles for the validation message are not applied
$('#maxRateforvalidation').show();
return false;
}
});
EDIT:
Here is the relevant part of code in cshtml page:
@using (Html.BeginForm("Saveaction", "mycontroller", FormMethod.Post))
{
..................
<dt>Rate</dt>
<dd>@Html.TextBoxFor(model => model.rate, new { style = "width:28%"})
@Html.ValidationMessageFor(model => model.rate)
</dd>
<dt>minRate</dt>
<dd>@Html.TextBoxFor(model => model.minrate, new { style = "width:28%"})
@Html.ValidationMessageFor(model => model.minrate)
</dd>
<dt>maxRate</dt>
<dd>@Html.TextBoxFor(model => model.maxrate, new { style = "width:28%"})
@Html.ValidationMessageFor(model => model.maxrate)
</dd>
.........................
<button type="submit" id="Save" > Save(F2)</button>
}
EDIT:
I checked the code generated at run-time, for rate field ,when I left it blank and click submit button:
<span id="minRateforvalidation" class="field-validation-error" data-valmsg-replace="true" data-valmsg-for="minRate" style="display: inline;">
<span class="" htmlfor="minRate" generated="true">Min.Rate Required</span>
</span>
So I updated the code like this:
if (parseFloat(maxrate) < parseFloat(rate)) {
$('#maxRateforvalidation').html('<span class="" htmlfor="maxRate" generated="true" style="visibility: hidden;">Max.Rate must be higher than rate</span>');
$('#maxRateforvalidation').addClass("field-validation-error");
$('#minRateforvalidation').show();
return false;
}
Now it works.. but only when I check the content with firebug and submit!! Cant figure out the reason. Is there any simpler way to perform this validation, like setting the range in the model itself as shown below:
[Required(ErrorMessage = "Min.Rate Required")]
[Range(1, rate, ErrorMessage = "Invalid Rate")]// cant do it.
public decimal minRate
{
get;
set;
}