简体   繁体   English

在JQuery中使用条件进行必要的字段验证

[英]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. 我需要为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: CSHTML:

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

JQuery: 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. 我是JQuery的新手,如果遗漏了某些内容,请告诉我。

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. 如果从列表中选择了值,则代码中的一个错误是嵌套函数不会返回true。

Edit: 编辑:

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

to make better use of jQuery validator. 更好地利用jQuery验证器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM