jQuery验证重复的错误消息/附加错误消息列表

时间:2016-11-28 22:51:13

标签: javascript jquery jquery-validate

我通过jQuery Validate的errorPlacement,wrapper,errorContainer,errorLabelContainer搜索了所有最近的帖子。

根据我的理解,如果我想在特定字段中 SELECTIVELY 列出(而不是全部)错误,则错误发布是我的方法。

最终目标是在标记顶部的errorContainer中显示其相应输入(默认行为)下方的每个错误,并在birthdate字段集之后放置的errorContainer中仅列出相关的“birthdate”错误(或仅附加在#year输入之后。

目前正在尝试使用errorPlacement将错误添加到我定位的其中一个字段中。但是,通过阅读JQV上的大量Sparky's帖子,使用append打破了本机隐藏/显示错误,我最终在我的标记中出现了大量重复的错误消息。使用innerHtml / html只会根据输入的模糊焦点列出一个错误。

^这是我目前的困境。

(奖金任务:我不确定我是否正确使用分组规则/错误消息/ required_from_group)

HTML:        

<!-- PROFILE INPUTS -->
<h2>Profile</h2>

<fieldset>
  <legend class="hidden">Profile</legend>
  <label for="firstname">First Name</label>
  <input id="firstname" class="form-input" type="text" name="firstname" placeholder="First Name" value="" autofocus>

  <label for="middleInitial">Middle Initial <span class="grey-tip">(optional)</span></label>
  <input class="form-input mi" type="text" name="middleInitial" id="middleInitial" placeholder="MI" value="">

  <label for="lastname">Last Name</label>
  <input id="lastname" class="form-input" type="text" name="lastname" placeholder="Last Name" value="">

  <label for="gender">Select a Gender</label>
  <select id="gender" class="form-input select-gender" name="gender" type="text">
    <option value="Select a Gender" disabled selected>Select a Gender</option>
    <option value="Female">Female</option>
    <option value="Male">Male</option>
    <option value="Nonbinary">Non Binary</option>
    <option value="Other">Prefer not to say</option>
  </select>

  <fieldset id="birthdate">
    <legend>Birthdate <span class="grey-tip">(mm/dd/yyyy)</span></legend>
    <label for="month" class="hidden">Month</label>
    <input id="month" class="form-input bd" name="month" type="number" placeholder="mm" value="">

    <label for="day" class="hidden">Day</label>
    <input id="day" class="form-input bd" name="day" type="number" placeholder="dd" value="">

    <label for="year" class="hidden">Year</label>
    <input id="year" class="form-input bd" name="year" type="number" placeholder="yyyy" value="">
  </fieldset>

  <div class="birthdate-error-container"></div>

  <label for="ssn" class="label-ssn">Social Security Number</label>
  <input id="ssn" class="form-input" name="ssn" type="tel" placeholder="xxx-xx-xxxx">

  <label for="ssnCapture" class="hidden">SSN</label>
  <input id="ssnCapture" class="hidden" type="text">

  <label for="alternateId" class="label-ssn">Alternate ID <span class="grey-tip">(optional)&nbsp;&nbsp;</span><a id="alternateTip" href="#">What is this?</a></label>

  <div class="more-info-box alternateId hidden">
    <p>If you do not have or do not wish to provide your Social Security Number, you may choose an alternate number for identification. First enter any 9-digit number in the Social Security Number field. You can then create an alternate ID of no more
      than 15 characters with any numbers or letters of your choosing.</p>
  </div>

  <input id="alternateId" class="form-input" name="alternateId" type="text" placeholder="Alternate ID" value="">
</fieldset>

<!-- FOOTER: NEXT BUTTON -->
<footer>
  <div class="bottom-nav">
    <a href="#" id="backToQuote">Back to Qoute</a>
    <input type="submit" id="nextButton" class="btn multi-btn primary inline-block" value="Next" form="personal_form">
  </div>
</footer>

JS:

    $(document).ready(function() {
    var errContainer    = $('.error-container'),
         bd_errContainer = $('.birthdate-error-container');
    var voptions = {
        debug : "true",
        rules : {
            firstname: "required",
            lastname: "required",
            gender: "required",
            month: {
                require_from_group: [3, '.bd']
            },
            day: {
                require_from_group: [3, '.bd']
            },
            year: {
                require_from_group: [3, '.bd']
            },
            ssn: "required",

        },
        groups: {
            birthdate: "month day year"
        },
        messages : {
            firstname: "Please enter your firstname",
            lastname: "Please enter your lastname",
            gender: "Please make a selection",
            month: "Please enter valid month (1-12)",
            day: "Please enter valid day (1-31)",
            year: "Please enter a valid year in yyyy format",
            birthdate: {
                require_from_group: "Please fully complete month, day, and year"
            },
            ssn: "Please enter a valid SSN"
        },
        errorPlacement: function(error, element) {
            if (element.attr("name") == "month" || element.attr("name") == "day" || element.attr("name") == "year") {
                console.log("date group if fired");
                bd_errContainer.html(error);
                errContainer.html(error);
                // error.appendTo(bd_errContainer);
                // error.appendTo(errContainer);
            } else {
                console.log("outer if fired");
                errContainer.html(error);
                // error.appendTo(errContainer);
            }
        }
    };

    //DEVONLY (JQUERY VALIDATE PROTOTYPING):
    $('#personal_form').validate(voptions);
}

小提琴(可能不起作用,目前在办公室通过https发布): https://jsfiddle.net/jnurbina/58u7fcqx/

1 个答案:

答案 0 :(得分:0)

编辑2016年11月30日:

提出了一个更简单的清洁解决方案。发现我可以使用&#34; showErrors&#34;方法与&#34; errorPlacement&#34; &安培; &#34;成功&#34;实现我想要的。 This SO文章帮助指导了我的方向。

MY JS:

//Element JQ selects
    var $ec = $('.error-container'),
        $bdec  = $('.bd-error-container');

    //JQV Parameters
    var voptions = {
        debug: "true",
        //DEVONLY: uncomment ignore to skip validating specific elements
        // ignore: "#firstname, #lastname, #gender, #ssn",
        errorPlacement: function(error, element) {
            var eln = element.attr("name");
            //If inline elements append to a container below that fieldset
            //Else append below input as normal
            if (eln == "month" || eln == "day" || eln == "year") {
                $bdec.append(error);
            } else {
                error.insertAfter(element);
            }
        },
        showErrors: function(errorMap, errorList) {
            var emel;
            this.defaultShowErrors();
            //For every error message in errorMap array
            //Create a string <label> element with corresponding 'class' and 'for' attr's
            //If label already exists in error-container replace it with itself
            //Else append a new errorLabel to error-container
            for(var em in errorMap) {
                emel = '<label class="error '+em+'-error" for="'+em+'">'+errorMap[em]+'</label>';
                if ($ec.find('.error.'+em+'-error').length >= 1) {
                    $ec.find('.error.'+em+'-error').replaceWith(emel);
                } else {
                    $ec.append(emel);
                }
            }
        },
        success: function(label) {
            var ecls = '.'+label.attr('id'),
                dtch = $ec.find(ecls);
            /* Clear errors from error-container since JQV only shows/hides errors below the input:
            - First check if any errorLabels exist
            - If they do, they are removed from DOM */
            if (dtch) {
                dtch.detach();
            }
        },
        rules: {
            firstname: "required",
            lastname: "required",
            gender: "required",
            month: {
                required: true,
                range: [01, 12],
                minlength: 2
            },
            day: {
                required: true,
                range: [01, 31],
                minlength: 2
            },
            year: {
                required: true,
                minlength: 4
            },
            ssn: {
                required: true
            }
        },
        messages: {
            firstname: "Please enter your firstname",
            lastname: "Please enter your lastname",
            gender: "Please make a selection",
            month: {
                required: "Please enter valid month (1-12)",
                minlength: "Please enter month in mm format"
            },
            day: {
                required: "Please enter valid day (1-31)",
                minlength: "Please enter day in dd format"
            },
            year: {
                required: "Please enter a valid year",
                minlength: "Please enter a valid year in yyyy format"
            },
            ssn: "Please enter a valid SSN"
        }
    };

    //DEVONLY (JQUERY VALIDATE PROTOTYPING):
    $('#personal_form').validate(voptions);