简体   繁体   English

如果另一个输入字段为空,如何使用非侵入式验证将输入字段设为必填字段?

[英]How to use unobtrusive validation to make an input field required field if another input field is empty?

I have a simple form with three different text boxes to enter the search criteria before a resultset can be returned. 我有一个带有三个不同文本框的简单表单,可以在返回结果集之前输入搜索条件。 Among the three fields I want to make two fields conditionally required if the other one is empty. 在这三个字段中,如果另一个字段为空,我想使两个字段成为条件字段。

In the attached screenshot the search form cannot be submitted without entering either the "Title" or "Performers" fields. 在所附的屏幕截图中,如果不输入“标题”或“表演者”字段,则无法提交搜索表单。 It is fine if both fields have values. 如果两个字段都具有值,那就很好。 I wanted to achieve this by making "Title" as a required field when "Performers" is empty. 我想通过在“表演者”为空时将“标题”作为必填字段来实现。 But my code below doesn't work. 但是我下面的代码不起作用。 I have the necessary validation at the server side. 我在服务器端进行了必要的验证。 I am looking for a client side solution. 我正在寻找客户端解决方案。

在此处输入图片说明

HTML Source code: HTML源代码:

<form id="searchWorkForm">
        <div class="contourField textfield">
            <label for="searchWorkTitle" class="fieldLabel">Title</label>
            <div class="search-input">
                <a id="searchWork" href="#" style="z-index: 2000; margin-top: 0;"><img src="/images/profile-search.png" alt="" style="z-index: 1000;" id="profileSearch" /></a>
                <input type="text" name="searchWorkTitle" id="searchWorkTitle" class="text caps" value="" placeholder="Title" data-val="true" data-val-requiredif="title is mandatory" data-val-requiredif-otherpropertyname="searchWorkPerformer">
                <span class="field-validation-valid" data-valmsg-for="searchWorkTitle" data-valmsg-replace="true"></span>
            </div>
        </div>
        <div class="contourField textfield">
            <label for="searchWorkWriter" class="fieldLabel">Writers</label>
            <div class="wideInput">
                <input type="text" name="searchWorkWriter" id="searchWorkWriter" class="text caps" value="" placeholder="Writer Name">
                <span class="field-validation-valid" data-valmsg-for="searchWorkWriter" data-valmsg-replace="true"></span>
            </div>
        </div>
        <div class="contourField textfield">
            <label for="searchWorkPerformer" class="fieldLabel">Performers</label>
            <div class="wideInput">
                <input type="text" name="searchWorkPerformer" id="searchWorkPerformer" class="text caps" value="" placeholder="Performer Name" data-val="true">
                <span class="field-validation-valid" data-valmsg-for="searchWorkPerformer" data-valmsg-replace="true"></span>
            </div>
        </div>
</form>

Client side validation code: 客户端验证代码:

$(function() {
    if ($.validator && $.validator.unobtrusive) {

        $.validator.addMethod("requiredif", function (value, element, params) {
            return !(value.length === 0 && $(params).val().length === 0);
        });

        $.validator.unobtrusive.adapters.add("requiredif", ["otherpropertyname"], function (options) {
            options.rules["requiredif"] = "#" + options.params.otherpropertyname;
            options.messages["requiredif"] = options.message;
        });
    }

    $("#searchWork").click(function() {

        if ($("#searchWorkForm").valid()) {
            // Make an Ajax Call and get the search result
        }
    });
}

You first need to move the $.validator.addMethod() and $.validator.unobtrusive.adapters.add() functions outside the $(function() { .. } 首先,您需要将$.validator.addMethod()$.validator.unobtrusive.adapters.add()函数移至$(function() { .. }之外$(function() { .. }

But based on the description of what your wanting to validate, then the code in your $.validator.addMethod() method should first check if the 'other property' ( searchWorkPerformer ) has a value, and if so return true . 但是基于对您要验证的内容的描述,然后$.validator.addMethod()方法中的代码应首先检查“其他属性”( searchWorkPerformer )是否具有值,如果是,则返回true If it does not, then check if searchWorkTitle has a value. 如果没有,请检查searchWorkTitle是否具有值。 If it has, then return true , otherwise its invalid, so return false . 如果有,则返回true ,否则返回无效值,因此返回false

// scripts for jquery, jquery.validate and jquery.validate.unobtrusive
<script>
    $.validator.addMethod("requiredif", function (value, element, params) {
        if ($(params).val().length === 0) {
            return true;
        } elseif (value.length === 0) {
            return false;
        }
        return true;
    });
    $.validator.unobtrusive.adapters.add("requiredif", ["otherpropertyname"], function (options) {
        options.rules["requiredif"] = "#" + options.params.otherpropertyname;
        options.messages["requiredif"] = options.message;
    });

    $(function() {
        $("#searchWork").click(function() {
            if ($("#searchWorkForm").valid()) {
                // Make an Ajax Call and get the search result
            }
        });
    }
</script>

Side note: requiredif does not really describe your validation - perhaps requiredifempty would be more appropriate since you only require a value if the other property is empty. 旁注: requiredif并未真正描述您的验证-也许requiredifempty会更合适,因为仅在其他属性为空时才需要一个值。

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

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