jQuery Validation Plugin不能忽略隐藏或禁用字段

时间:2013-12-16 00:03:56

标签: jquery asp.net-mvc jquery-validate hidden-field

我使用jQuery Validation Plugin,我想验证除了其他字段之外的一些隐藏/禁用字段。虽然每个字段都可以正确验证,但我在隐藏/禁用字段方面遇到了一些问题。此时:

1)我根据下拉列表选择值的值隐藏文本框字段。哪种方法更适合验证此字段:disabled = true / false或hide / show?或者他们两个同时?

2)对于将根据Dropdownlist值隐藏/禁用的Textbox字段,我是否应该在相关的Entity模型中将其设为Required?如果是,则相同字段被假定为必填字段,并且即使隐藏/禁用也尝试进行验证。

3)另一方面,当我在实体模型中没有使用相关字段的必需时,即使我输入如下所示,它也不会被验证:


jQuery(function () {
    $("#myform").validate({
        onfocusout: false,

        rules: {
            'Applicant.workingSoot': "required"
        },

        messages: {
            'Applicant.workingSoot': {
                required: "Make is required!"
            }
        },

        submitHandler:
            $("#myform").on('submit', function () {
                if ($("#myform").valid()) {
                    //Do something here
                    alert("Validation passed");
                }
                return false;
            })
    });
});


注意:我使用javascripts进行验证,具体如下:

<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>



更新

Layout.cshtml:

<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>


查看:

<script type="text/javascript">   

    //It is used for show/hide fields according to the related 
Dropdownlist selected value
    function showHideWorking() {
        var $index = $('#isWorking').val();
        if ($index == '31') {          
            $('#workingSoot').show(); 
            $('#lbworkingSoot').show(); 
            $('#workingCity').show(); 
            $('#lbWorkingCity').show(); 

            //disabling fields in addition to hiding
            $('#lbworkingSoot').disabled = false;
            $('#workingCity').disabled = false;
            //            
        }
        else {
            $('#workingSoot').hide(); 
            $('#lbworkingSoot').hide();
            $('#workingSoot').val(""); 

            $('#workingCity').hide(); 
            $('#lbWorkingCity').hide(); 
            $('#workingCity').val(""); 

            //disabling fields in addition to hiding
            $('#lbworkingSoot').disabled = true;
            $('#workingCity').disabled = true;
            //
        }
    }
</script>

<script type="text/javascript">
/* <![CDATA[ */   /* Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA. */
jQuery(function () {

    $.validator.setDefaults({
        // options for all forms on page
    });

    $("#addForm").validate({
        onfocusout: false,

        rules: {
            'Applicant.identityNumber': "required",
            'Applicant.name': "required",
            'Applicant.surname': "required",
            'Applicant.telephone': "required",
            'Applicant.email': "required",
            'Applicant.organization': "required",
            'Applicant.hasDoneAnyProject': "required",
            'Applicant.isInterestedAnyProgramme': "required",
            'Applicant.meetingId': "required",
            'Applicant.isWorking': "required",

            //displayed & hidden fields:
            'Applicant.workingSoot': "required",
            'Applicant.workingCity': "required" 
        },

        submitHandler:
            $("#addForm").on('submit', function () {
                if ($("#addForm").valid()) {
                    //Do something here
                    alert("Validation passed");
                }
                return false;
            })
    });
});
/* ]]> */


@using (Html.BeginForm("Add", "Applicant", FormMethod.Post,
new { id="addForm", enctype = "multipart/form-data" }))
{    
    <div class="container">
        <fieldset>
            @Html.LabelFor(m=>m.Applicant.IdentityNumber)
            @Html.TextBoxFor(m => m.Applicant.IdentityNumber, new { maxlength = 11, name = "identityNumber", id = "identityNumber", @class = "numbers_only" }) 
            @Html.ValidationMessageFor(m => m.Applicant.IdentityNumber, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.Name)
            @Html.TextBoxFor(m => m.Applicant.Name, new { maxlength = 30, name = "name", id = "name", @class = "letters_only" })
            @Html.ValidationMessageFor(m => m.Applicant.Name, null , new { @class = "ValidationErrors" }) 

            @Html.LabelFor(m=>m.Applicant.Surname)
            @Html.TextBoxFor(m => m.Applicant.Surname, new { maxlength = 30, name = "surname", id = "surname", @class = "letters_only" })
            @Html.ValidationMessageFor(m => m.Applicant.Surname, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.Telephone)
            @Html.TextBoxFor(m => m.Applicant.Telephone, new { maxlength = 11, name = "telephone ", id = "telephone", @class = "phone_uk" })
            @Html.ValidationMessageFor(m => m.Applicant.Telephone, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.Email)
            @Html.TextBoxFor(m => m.Applicant.Email, new { maxlength = 50, name = "email", id = "email" })
            @Html.ValidationMessageFor(m => m.Applicant.Email, null , new { @class = "ValidationErrors" })
        </fieldset>

        <fieldset>
            @Html.LabelFor(m=>m.Applicant.IsWorking)
            @Html.DropDownListFor(m => m.Applicant.IsWorking, new SelectList(Model.Lookups.Where(x => x.LookupType == "Working"),
           "LookupID", "LookupValue"), "---- Select ----", new { name = "isWorking", id = "isWorking", onchange="showHideWorking()"}) 
            @Html.ValidationMessageFor(m => m.Applicant.IsWorking, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.WorkingSoot, new { name = "lbworkingSoot", id = "lbworkingSoot" })
            @Html.TextBoxFor(m => m.Applicant.WorkingSoot, new { maxlength = 50, name = "workingSoot", id = "workingSoot" })
            @Html.ValidationMessageFor(m => m.Applicant.WorkingSoot, null , new { @class = "ValidationErrors" })

            @Html.LabelFor(m=>m.Applicant.WorkingCity, new { name = "lbWorkingCity", id = "lbWorkingCity"})
            @Html.DropDownListFor(m => m.Applicant.WorkingCity, new SelectList(Model.Cities,
           "CityID", "CityName"), "---- Select ----", new { name = "workingCity", id = "workingCity"}) 
            @Html.ValidationMessageFor(m => m.Applicant.WorkingCity, null , new { @class = "ValidationErrors" })
        </fieldset>      

        <input id="submitbtn" type="submit" value="Send" class="button" />
    </div>     
}

2 个答案:

答案 0 :(得分:1)

  • submitHandler将一个函数作为参数,指定在成功验证表单时要执行的操作。例如:

     submitHandler:function(form){
           alert('Validation passed');
     }
    
  • 默认情况下,jQuery Validate不会验证隐藏字段。因此,如果您根据下拉列表的值隐藏字段,则不会以任何方式对其进行验证。

答案 1 :(得分:0)

您似乎无法理解submitHandler回调函数的工作原理......

submitHandler:                               // <- "function() {" is missing
    $("#myform").on('submit', function () {  // <- redundant
       if ($("#myform").valid()) {           // <- redundant
          //Do something here
          alert("Validation passed");
        }
        return false;
     })
                                             // <- closing brace } is missing
  • 作为回调的一部分,您错过了function()和大括号{ }。应该是

    submitHandler: function(form) {
        ...
    }
    
  • submitHandler 触发提交按钮的click事件(当表单有效时),因此绝对没有办法< / strong>你需要在其中放置一个.on('submit')处理程序。我怀疑它是否可行,因为该插件阻止了默认的submit事件,因此它可以验证表单。

  • 由于只有submitHandler 在表单生效时触发(按钮点击),因此无需再使用if .valid()对其进行测试。

删除代码中的所有冗余...

submitHandler: function(form) { // only fires on button click when form is valid 
    // Do something here
    alert("Validation passed");
    return false;
}

默认情况下,此插件将忽略所有隐藏字段。要对隐藏字段启用验证,请按以下方式设置ignore选项...

ignore: []

如果您想根据其他内容切换验证规则,请使用depends方法或使用.rules('add').rules('remove')方法动态添加/删除规则。

但是,由于您尚未真正展示自己想要做的事情,也没有展示任何HTML标记,因此我只建议您学习the documentation并查看the hundreds of code examples posted on Stack Overflow