显示/隐藏动态错误消息并防止默认

时间:2018-03-17 10:18:06

标签: javascript forms validation

我有一个简单的表单来验证,我不能使用jQuery validate()。

我发了两条错误消息 - 一封用于复选框,另一封用于确认电子邮件不匹配。

这是表格

<!doctype html>
<html>

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
  <title>testForm</title>
  <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  </head>

<body>
  <div class="container main">
    <div class="row">
      <div class="col-sm-8 col-sm-offset-2 logo">
        <p class="text-center">Use this form to request more information.</p>
        <div class="well">
          <form name="enrol" id="enrol" xmp-register class="form-horizontal">
            <div class="form-group" id="checkboxGroup">
              <div class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8">
                <div class="checkbox">
                  <label>
                    <input type="checkbox" id="flexi" name="checkBoxes"> Yes, email me more information about Scheme 1</label>
                </div>
              </div>
              <div class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8">
                <div class="checkbox">
                  <label>
                    <input type="checkbox" id="kiwi" name="checkBoxes"> Yes, email me more information about Scheme 2</label>
                </div>
              </div>
              <div class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8">
                <div class="checkbox">
                  <label>
                    <input type="checkbox" id="protect" checkBoxes="protect"> Yes, email me more information about Scheme 3</label>
                </div>
              </div>
            </div>

            <div class="form-group">
              <label for="firstName" class="col-md-3 col-lg-4 control-label"> First name </label>
              <div class="col-md-8 col-lg-7">
                <input type="text" name="firstName" maxlength="42" class="form-control" required>
              </div>
            </div>
            <div class="form-group">
              <label for="lastName" class="col-md-3 col-lg-4 control-label"> Last name </label>
              <div class="col-md-8 col-lg-7">
                <input type="text" name="lastName" maxlength="42" class="form-control" required>
              </div>
            </div>
            <div id="emailGroup">
              <div class="form-group">
                <label for="email" class="col-md-3 col-lg-4 control-label"> Email address </label>
                <div class="col-md-8 col-lg-7">
                  <input type="email" id="email" name="email" class="form-control" required>
                </div>
              </div>

              <div class="form-group">
                <label for="confirmEmail" class="col-md-3 col-lg-4 control-label"> Confirm email address </label>
                <div class="col-md-8 col-lg-7">
                  <input type="email" id="confirmEmail" name="confirmEmail" class="form-control" required>
                </div>
              </div>

            </div>
            <div class="form-group">
              <label for="contact-number" class="col-md-3 col-lg-4 control-label"> Contact number </label>
              <div class="col-md-4">
                <input type="text" name="contactNumber" class="form-control" pattern="\d+">
              </div>
              <div class="col-md-4 col-lg-3">
                <select name="contactNumberType" class="form-control">
                  <option value="" disabled="disabled" selected="selected">Type</option>
                  <option value="mobile">Mobile</option>
                  <option value="business-hours">Business Hours</option>
                  <option value="after-hours">After Hours</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label for="memberNumber" class="col-md-3 col-lg-4 control-label" style="padding-top:0px;"> Member number
                <br>(if you already have one)</label>
              <div class="col-md-8 col-lg-7">
                <input type="number" name="memberNumber" class="form-control">
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-3 col-md-offset-1">
                <input id="submitBtn" name="submitBtn" type="submit" value="Complete" class="form-control btn btn-primary">
              </div>
            </div>
        </div>
        </form>
      </div>
    </div>
  </div>
  </div>

  <!--[if lte IE 7]>
<script src="https://raw.github.com/mattpowell/localstorageshim/master/localstorageshim.min.js" type="text/javascript"></script>
<![endif]-->

  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>


  <!-- WM coding -->
  <script src="so.js"></script>


</body>

</html>

这是JS

    $(document).ready(function () {
// set flags to control error messages
    var emailError = false;
    var selectionError=false;
    $("#submitBtn").click({
    // validation checks performed on submit:
    // 1. check that at least one checkbox is checked
    emailError,selectionError // passing parameters to click function
    }, function (event) {
        var flexibox = document.getElementById("flexi");
        var kiwibox = document.getElementById("kiwi");
        var protectbox = document.getElementById("protect");
        var mainEmail = document.getElementById("email").value;
        var confirmEmail = document.getElementById("confirmEmail").value;

        var noSelection = checkRequest();   // check if selection made
        var emailMismatch = checkEmails(mainEmail, confirmEmail);
        console.log(noSelection);
        if (noSelection || emailMismatch) {    // checks the first element of variable returned
            event.preventDefault();
        }

        function checkRequest() {
            if (protectbox.checked == false && (kiwibox.checked == false && flexibox.checked == false)) { //no option selected
                if (selectionError === false) { // if no error message showing
                    $("#checkboxGroup").after( // add error message
                        '<div id="noSelect" class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8"><p style="color:red;">Please select at least one option.</p></div>'
                    );
                    selectionError = true; //update flag to avoid multiple error messages on repeated submit attempts
                }
                return selectionError;  // exit
            } else {    // something is selected
                $("#noSelect").remove();    // remove error message
                selectionError=false;   //reset flag
                return selectionError;  //exit
            }
        }

        function checkEmails(mainEmail, confirmEmail) {
            if (mainEmail != confirmEmail) { //2. email addresses don't match
            if (emailError === false) { // if no error message showing
                $("#emailGroup").after( // add error message
                    '<div id="emailMismatch" class="col-md-offset-3 col-lg-offset-4 col-md-8 col-lg-8"><p style=color:red;">Please ensure the email addresses match.</p></div>'
                );
                emailError = true; //update flag to avoid multiple error messages on repeated submit attempts
            }
                return true;
            } else if (mainEmail == "" || confirmEmail == "") { // to stop email error message showing when the fields haven't been filled
                return emailError;
            } else {
                return emailError;
            }

        }
    });
});

// force Sarari to honour required attributes
jQuery.getScript('https://cdnjs.cloudflare.com/ajax/libs/webshim/1.15.7/minified/polyfiller.js')     .done(function () {         
    webshims.polyfill('forms');          
});

我遇到的问题是复选框组错误消息隐藏并显示每次提交尝试时 - 工作正常,但电子邮件不匹配错误显示一次,然后无法删除并且即使电子邮件不匹配已得到纠正,表单也不会提交。

当我在Chrome中检查页面并单步执行代码时,我可以看到电子邮件检查的两个变量,&#34; mainEmail&#34;和&#34; confirmEmail&#34;匹配,但会跳过以下语句,就好像它们不匹配一样。

如果有人能给我一些帮助,我真的很感激。我确信代码不必要地冗长 - 我几乎是初学者。

谢谢和问候,

马尔科姆

1 个答案:

答案 0 :(得分:0)

您不会取消设置错误消息,也不会将emailError设置为false。将checkEmail的else块更改为

else {
        emailError = false;
        $("emailMismatch").remove();
        return emailError;
    }