user2480288
user2480288

Reputation: 639

Required field validation with conditions in JQuery

I need to add a condition clause for a required field validation for a drop down list in MVC. I tried to use custom validation but it doesn't seem to work.

I need to check if the travel type drop down is selected as "Select Travel", then required validation should fire.

I have set a required field attribute at the Travel Model for Travel Type Attribute.

cshtml:

 <td>@Html.ValidationMessageFor(m => m.Travel.TravelType)</td>

JQuery:

 $travelType = $("#travel");
       jQuery.validator.addMethod("TravelType",
                function () {
                    if ($travelType.val() == "Select Travel" || $vehicleType.val() == null)
                        return false;

                    $("#travel").rules("add", "TravelType");
                });

I am new to JQuery, please let me know if a missing something.

Upvotes: 0

Views: 1188

Answers (1)

jHilscher
jHilscher

Reputation: 1868

jQuery.validator.addMethod("TravelType", function (value, element, param) {
                    // return true if valid, false if not
        return $("#travel").val() && $("#travel").val() != "Select Travel";
    });
jQuery.validator.unobtrusive.adapters.addBool("TravelType");

Here would be an example how to implement it. One mistake in your code is, that the nested function will not return true, if a value is selected from the list.

Edit:

return value && value != "Select Travel";

to make better use of jQuery validator.

Upvotes: 2

Related Questions