0

我的 mvc3 页面中有三个字段:rate、minrate 和 maxrate。速率应高于 minrate 并小于 maxrate。如何通过 mvc3 模型验证来实现这一点?这是模型:

   [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;
    }

编辑:

我尝试在客户端使用 javascript 进行比较。如果我能找到一种动态更改验证消息的方法(例如:在 maxrate 字段的情况下为“所需的最大速率”),我可以解决问题。有没有办法做到这一点?

我试过这个:(省略了一些代码)

//...........................
$('#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;
             }
});

编辑:

这是cshtml页面中代码的相关部分:

  @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>

}

编辑:

我检查了运行时生成的代码,对于 rate 字段,当我将其留空并单击提交按钮时:

<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>

所以我更新了这样的代码:

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;
                }

现在它可以工作了..但只有当我用萤火虫检查内容并提交时!想不通原因。有没有更简单的方法来执行这个验证,比如在模型本身中设置范围,如下所示:

 [Required(ErrorMessage = "Min.Rate Required")]
       [Range(1, rate, ErrorMessage = "Invalid Rate")]// cant do it.

        public decimal minRate
        {
            get;
            set;
        }
4

0 回答 0