0

I have to validate a field only if a previous field is $0.01 or more. I am using asp.net mvc to code this. My page looks like this:

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

I have required tags in my model on both fields.

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

What type of code would I need to write in the HomeController.cs to only validate that field if the amount is greater than .01 or remove validation if the amount is equal to 0.00?

I've tried this to no success

if (model.AdditionalIncomeAmt == null)
        {
            this.ModelState.Remove("AdditionalIncomeSource");
        }
TheDizzle
  • 1,534
  • 5
  • 33
  • 76
  • I don't believe this functionality is built into the framework. You'd either have to write your own validation attribute. I'd recommend checking out Fluent Validation - http://fluentvalidation.codeplex.com/ which is much more flexible. In this case you could say When(m => m.SomeField > 0.01, – Adam May 27 '14 at 04:06
  • possible duplicate of [client-side validation in custom validation attribute - asp.net mvc 4](http://stackoverflow.com/questions/19726404/client-side-validation-in-custom-validation-attribute-asp-net-mvc-4) – Liam May 29 '14 at 13:56

1 Answers1

0

Writing your own validation function in javascript will be the easiest way here.

$('#btnSubmit').click(function(){
    if(your condition true)
    {
        $('form').submit()
    }
    else
    {
         // show validation
    }
});
chandresh patel
  • 309
  • 1
  • 10