只有当另一个字段超过一定数量时,才验证一个字段

本文关键字:字段 一个 验证 另一个 | 更新日期: 2023-09-27 18:05:22

只有当前一个字段大于等于$0.01时才需要验证该字段。我使用asp.net mvc来编写此代码。我的页面是这样的:

<div class="form-group">
                @Html.LabelFor(m => m.AdditionalIncomeAmt, new { @class = "col-sm-2 control-label" })
                <div class="col-sm-10">
                    <div class="col-sm-4">
                        @Html.TextBoxFor(m => m.AdditionalIncomeAmt, new { @class = "form-control", placeholder = "Additional Income Amount", id = "additionalIncome" })
                        @Html.ValidationMessageFor(m => m.AdditionalIncomeAmt)
                    </div>
                </div>
            </div>
            <div class="form-group">
                @Html.LabelFor(m => m.AdditionalIncomeSource, new { @class = "col-sm-2 control-label" })
                <div class="col-sm-10">
                    <div class="col-sm-4">
                        @Html.TextBoxFor(m => m.AdditionalIncomeSource, new { @class = "form-control", placeholder = "Additional Income Source", id = "additionalIncomeSource" })
                        @Html.ValidationMessageFor(m => m.AdditionalIncomeSource)
                    </div>
                </div>
            </div>

我在模型的两个字段上都有必需的标签。

    [Required(ErrorMessage = "Additional income amount is required")]
    [Display(Name = "Additional Income Amount")]
    public string AdditionalIncomeAmt { get; set; }
    [Required(ErrorMessage = "Additional income source is required")]
    [Display(Name = "Additional Income Source (If any)")]
    public string AdditionalIncomeSource { get; set; }

我需要在HomeController.cs中编写什么类型的代码来仅在金额大于0.01时验证该字段,或者在金额等于0.00时删除验证?

I've try this to no success

if (model.AdditionalIncomeAmt == null)
        {
            this.ModelState.Remove("AdditionalIncomeSource");
        }

只有当另一个字段超过一定数量时,才验证一个字段

在javascript中编写自己的验证函数将是最简单的方法。

$('#btnSubmit').click(function(){
    if(your condition true)
    {
        $('form').submit()
    }
    else
    {
         // show validation
    }
});