在不重新加载页面的情况下验证表单

Validate form without page reload

本文关键字:情况下 表单 验证 加载 新加载      更新时间:2023-09-26

我正在实现一个简单的注册表单。我想验证用户是否选择了至少一个checkbox。除了这一个输入字段外,我的表单中的所有字段都在没有重新加载页面的情况下进行验证。当我尝试验证这个字段时,页面会重新加载,用户之前输入的所有值都会丢失。我想防止这种情况发生。

    function validate() {
    var checkbox1 = document.getElementById('three').checked;
    var checkbox2 = document.getElementById('four').checked;
    var checkbox3 = document.getElementById('five').checked;
    var checkbox4 = document.getElementById('six').checked;
    if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == true) {
        if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
            alert("Please enter all the required values");
        } 
    } 
    if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
        if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
            alert("Please enter all the required values");
        } 
    } 
    if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
        if (referenceToForm.elements["usrgrp[]"].selectedIndex != -1) {
            alert("Please enter all the required values");
        }  
    } 
    if (document.getElementById('values').value == -1) {
        alert("Please enter all the required values checkbox");
    }
}
@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");
#labels{
    position: relative;
    width: 250px;
    float: left;
}
h3{
    margin: 0px 0px 20px 0px;
}
#fields{
    position: relative;
    width: 250px;
    float: left;
}
.element{
    margin-bottom: 23px;
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}
.different{
    margin-top: 4px;
    margin-bottom: 22px;
}
.values{
    margin-bottom: 23px;
}
.heading, .feedback{
    margin-top: 43px;
}
.preference{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}
.multiple{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    margin-top: 20px;
}
textarea{
    margin-top: 20px;
    border: 1px solid  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}
a{
    color: #06a3e9;
}
.final{
    margin-top: 15px;
}
.feedback{
    margin-top: 73px;
}
#submit, #reset{
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    border-radius:5px;
}
input[type="checkbox"]{
    display: none;
}
label:before{
    width: 1em;
    display: inline-block;
}
label{
    margin-right: 5px;
}
input[type="checkbox"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content: "'f096";
    letter-spacing: 5px;
    color: #06a3e9;
    display: inline-block;
}
input[type="checkbox"]:checked + label:before{
    content:"'f14a";
    display: inline-block;
    color: #06a3e9;
}
input[type="radio"]{
    display: none;
}
input[type="radio"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content:"'f10c";
    font-size: 14px;
    color: #06a3e9;
    letter-spacing: 5px;
    display: inline-block;
}
input[type="radio"]:checked + label:before{
    content:"'f192";
    font-size: 14px;
    display: inline-block;
}
<!doctype html>
<html>
  <head>
    <title> Register here </title>
    <link rel="stylesheet" href="../css/registration.css"/>
    <script src = "../javascript/registration.js"></script>
  </head>
  <body>
        <h1>Event Registration Form</h1>
        <div id="labels">
            <h3>Username</h3>
            <h3>Password</h3>
            <h3>Age</h3>
            <h3>Email</h3>
            <h3>Existing customer?</h3>
            <h3>Select your preferences</h3>
            <h3>Newsletter Preferences</h3>
            <h3 class="heading">Menu Options</h3>
            <h3 class="feedback">Send us your feedback !</h3>
        </div>
        <div id="fields">
            <form action="#" method="get" name="referenceToForm">
                <input type="text" name="Username" id="Username" class="element"required/>
                <input type="password" name="Password" class="element" required/>
                <input type="number" name="Age" class="element" required/>
                <input type="email" name="Email" class="element" required/>
            <div class="different">
              <input type="radio" name="customer" id="one" checked="checked" />
              <label for="one">Yes</label>
              <input type="radio" name="customer" id="two" />
              <label for="two">No</label>
            </div>
            <div class="values">
              <input type="checkbox" name="interest" id="three" />
              <label for="three">Dog</label>
              <input type="checkbox" name="interest" id="four" />
              <label for="four">Cat</label>
              <input type="checkbox" name="interest" id="five" />
              <label for="five">Parrot</label>
              <input type="checkbox" name="interest" id="six" />
              <label for="six">Possum</label>
              <span id="spanning"> </span>
            </div>
            <select class="preference" id="preference" value="-1">
                <option value="Entertainment">Entertainment</option>
                <option value="Technology">Technology</option>
                <option value="TV">TV</option>
            </select>
        
            <div class="menu">
                <select multiple required id="multiple" class="multiple" value="-1" name="usrgrp[]">
                    <option value="Sports">Sports</option>
                    <option value="Politics">Politics</option>
                    <option value="News">News</option>
                    <option value="Swimming">Swimming</option>
                    <option value="Health">Health</option>
                </select>
            </div>
        
            <textarea rows="5" cols="20" required></textarea>
        
            <div class="final">
                <input type="submit" name="submit" id="submit" onclick="validate()" />
                <input type="reset" name="reset" id="reset" />
            </div>
      </form>
    </div>
  </body>
</html>

感谢所有试图帮助我的人。下面的代码完美地解决了我的问题。

function validate() {
    
    var checkbox1 = document.getElementById('three').checked;
        var checkbox2 = document.getElementById('four').checked;
        var checkbox3 = document.getElementById('five').checked;
        var checkbox4 = document.getElementById('six').checked;
    
        if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
                alert("Please enter all the required values");
                return false;
        } 
    }
@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");
    
    #labels{
        position: relative;
        width: 250px;
        float: left;
    }
    
    h3{
        margin: 0px 0px 20px 0px;
    }
    
    #fields{
        position: relative;
        width: 250px;
        float: left;
    }
    
    .element{
        margin-bottom: 23px;
        border: 1px solid #dadada;
        border-color:  #06a3e9;
        box-shadow: 0 0 1px lightblue;
    }
    
    .different{
        margin-top: 4px;
        margin-bottom: 22px;
    }
    
    .values{
        margin-bottom: 23px;
    }
    
    .heading, .feedback{
        margin-top: 43px;
    }
    
    .preference{
        border-color:  #06a3e9;
        box-shadow: 0 0 1px lightblue;
    }
    
    .multiple{
        border-color:  #06a3e9;
        box-shadow: 0 0 1px lightblue;
        margin-top: 20px;
    }
    
    textarea{
        margin-top: 20px;
        border: 1px solid  #06a3e9;
        box-shadow: 0 0 1px lightblue;
    }
    
    a{
        color: #06a3e9;
    }
    
    .final{
        margin-top: 15px;
    }
    
    .feedback{
        margin-top: 73px;
    }
    
    #submit, #reset{
        border: 1px solid #dadada;
        border-color:  #06a3e9;
        box-shadow: 0 0 1px lightblue;
        border-radius:5px;
    }
    
    input[type="checkbox"]{
        display: none;
    }
    
    label:before{
        width: 1em;
        display: inline-block;
    }
    
    label{
        margin-right: 5px;
    }
    
    input[type="checkbox"] + label:before{
        font-family: FontAwesome;
        display: inline-block;
        content: "'f096";
        letter-spacing: 5px;
        color: #06a3e9;
        display: inline-block;
    }
    
    input[type="checkbox"]:checked + label:before{
        content:"'f14a";
        display: inline-block;
        color: #06a3e9;
    }
    
    input[type="radio"]{
        display: none;
    }
    
    input[type="radio"] + label:before{
        font-family: FontAwesome;
        display: inline-block;
        content:"'f10c";
        font-size: 14px;
        color: #06a3e9;
        letter-spacing: 5px;
        display: inline-block;
    }
    
    input[type="radio"]:checked + label:before{
        content:"'f192";
        font-size: 14px;
        display: inline-block;
    }
<!doctype html>
    <html>
    
      <head>
        <title> Register here </title>
        <link rel="stylesheet" href="../css/registration.css"/>
        <script src = "../javascript/registration.js"></script>
      </head>
    
      <body>
            <h1>Event Registration Form</h1>
    
            <div id="labels">
                <h3>Username</h3>
                <h3>Password</h3>
                <h3>Age</h3>
                <h3>Email</h3>
                <h3>Existing customer?</h3>
                <h3>Select your preferences</h3>
                <h3>Newsletter Preferences</h3>
                <h3 class="heading">Menu Options</h3>
                <h3 class="feedback">Send us your feedback !</h3>
            </div>
    
            <div id="fields">
                <form action="#" method="get" name="referenceToForm">
                    <input type="text" name="Username" id="Username" class="element"required/>
                    <input type="password" name="Password" class="element" required/>
                    <input type="number" name="Age" class="element" required/>
                    <input type="email" name="Email" class="element" required/>
    
                <div class="different">
                  <input type="radio" name="customer" id="one" checked="checked" />
                  <label for="one">Yes</label>
                  <input type="radio" name="customer" id="two" />
                  <label for="two">No</label>
                </div>
    
                <div class="values">
                  <input type="checkbox" name="interest" id="three" />
                  <label for="three">Dog</label>
                  <input type="checkbox" name="interest" id="four" />
                  <label for="four">Cat</label>
                  <input type="checkbox" name="interest" id="five" />
                  <label for="five">Parrot</label>
                  <input type="checkbox" name="interest" id="six" />
                  <label for="six">Possum</label>
                  <span id="spanning"> </span>
                </div>
    
                <select class="preference" id="preference" value="-1">
                    <option value="Entertainment">Entertainment</option>
                    <option value="Technology">Technology</option>
                    <option value="TV">TV</option>
                </select>
            
                <div class="menu">
                    <select multiple required id="multiple" class="multiple" value="-1" name="usrgrp[]">
                        <option value="Sports">Sports</option>
                        <option value="Politics">Politics</option>
                        <option value="News">News</option>
                        <option value="Swimming">Swimming</option>
                        <option value="Health">Health</option>
                    </select>
                </div>
            
                <textarea rows="5" cols="20" required></textarea>
            
                <div class="final">
                    <input type="submit" name="submit" id="submit" onclick="return validate()" />
                    <input type="reset" name="reset" id="reset" />
                </div>
          </form>
        </div>
      </body>
    </html>

我发现你的表单有两个问题,这两个问题都很容易解决。

验证函数必须返回true来提交表单,或者返回false来取消。如果不像代码中那样提供返回值,则表单将始终被提交:

<input type="submit" name="submit" id="submit" onclick="validate()" >

要解决这个问题,你需要让你的验证函数返回一个值,该值返回给onclick处理程序:

<input type="submit" name="submit" id="submit" onclick="return validate()" >

验证函数中的这一行抛出错误,因为没有id="values"的元素。您需要删除或修复此代码,以便您的函数正常完成并返回true或false值。

if (document.getElementById('values').value == -1) {
    alert("Please enter all the required values checkbox");
}

也许有人可以对此发表评论,但我总是看到在表单onsubmit事件中处理验证,而不是提交按钮onclick事件。然而,也许这只是一种惯例,因为它似乎两种方式都有效:

<form onsubmit="return validate()" ...
<input type="submit" onclick="return validate()" ...

如果使用jsFiddle,最重要的是使用以下方法初始化函数:

window.validate = function() {

而不是像这样:

function validate() {
这是我的尝试。没有使用Angular和JQuery,尽管我建议学习它们。我搞砸了你的提交按钮,但它很容易与css修复。我还添加了一个假的提交按钮,它只触发验证。如果通过验证,则可以继续发送。我的jsfiddle: http://jsfiddle.net/omikey/tfk7d3ks/

<div class="container">
 <div id="labels">
        <h3>Username </h3>
        <h3>Password</h3>
        <h3>Age</h3>
        <h3>Email</h3>
        <h3>Existing customer?</h3>
        <h3>Select your preferences</h3>
        <h3>Newsletter Preferences</h3>
        <h3 class="heading">Menu Options</h3>
        <h3 class="feedback">Send us your feedback !</h3>
     </div>
    <div id="fields">
      <form action="#" method="get" name="referenceToForm">
        <div>
          <input type="text" name="Username" id="Username" class="element" required/>
        </div>
        <div>
          <input type="password" name="Password" class="element" required/>
        </div>
        <div>
          <input type="number" name="Age" class="element" required/>
        </div>
        <div>
          <input type="email" name="Email" class="element" required/>
        </div>
        <div class="different">
          <input type="radio" name="customer" id="one" checked="checked" />
          <label for="one">Yes</label>
          <input type="radio" name="customer" id="two" />
          <label for="two">No</label>
        </div>
        <div class="value">
          <input type="checkbox" name="interest" id="three" />
          <label for="three">Dog</label>
          <input type="checkbox" name="interest" id="four" />
          <label for="four">Cat</label>
          <input type="checkbox" name="interest" id="five" />
          <label for="five">Parrot</label>
          <input type="checkbox" name="interest" id="six" />
          <label for="six">Possum</label>
          <span id="spanning"> </span>
        </div>
        <div>
          <select class="preference" id="preference" value="-1">
            <option value="Entertainment">Entertainment</option>
            <option value="Technology">Technology</option>
            <option value="TV">TV</option>
          </select>
        </div>
        <div class="menu">
          <select multiple id="multiple" class="multiple" value="-1" name="usrgrp[]">
            <option value="Sports">Sports</option>
            <option value="Politics">Politics</option>
            <option value="News">News</option>
            <option value="Swimming">Swimming</option>
            <option value="Health">Health</option>
          </select>
          <span id="spanElement"> </span>
        </div>
        <div class="comment">
          <textarea rows="5" cols="20" required></textarea>
        </div>
        <div class="final">
            <input type="button" name="verify" onclick="validate()" />
          <input type="submit" name="submit" style="display:none" id="submit" />
          <input type="reset" name="reset" id="reset" />
        </div>
      </form>
    </div>
</div>
    @import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css");
.container{
    width: 100%;
    margin-left: 400px;
}
#spanning{
    color: #06a3e9;
}
.nav ul{
    width: 150px;
    float: left;
    background-color: #dadada;
    padding: 0px;
    margin: 0px;
}
.nav li{
    list-style-type: none;
}
.nav a{
    color:#000;
    cursor:pointer;
    display: block;
    line-height: 40px;
    text-indent: 10px;
    text-decoration: none;
    font-weight: bold;
}
.nav ul ul li{
    display: none;
}
.nav li:hover ul li{
    display: block;
}
.subnav ul{
    position: relative;
    background: #dadada;
}
#labels{
    position: relative;
    width: 250px;
    top:80px;
    float: left;
}
h3{
    margin: 0px 0px 20px 0px;
}
#fields{
    position: relative;
    width: 250px;
    top:80px;
    float: left;
}
.element{
    margin-bottom: 23px;
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}
.different{
    margin-top: 4px;
    margin-bottom: 22px;
}
.value{
    margin-bottom: 23px;
}
.heading, .feedback{
    margin-top: 43px;
}
.preference{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}
.multiple{
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    margin-top: 20px;
}
textarea{
    margin-top: 20px;
    border: 1px solid  #06a3e9;
    box-shadow: 0 0 1px lightblue;
}
a{
    color: #06a3e9;
}
.final{
    margin-top: 15px;
}
.feedback{
    margin-top: 73px;
}
#submit, #reset{
    border: 1px solid #dadada;
    border-color:  #06a3e9;
    box-shadow: 0 0 1px lightblue;
    border-radius:5px;
}
input[type="checkbox"]{
    display: none;
}
label:before{
    width: 1em;
    display: inline-block;
}
label{
    margin-right: 5px;
}
input[type="checkbox"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content: "'f096";
    letter-spacing: 5px;
    color: #06a3e9;
    display: inline-block;
}
input[type="checkbox"]:checked + label:before{
    content:"'f14a";
    display: inline-block;
    color: #06a3e9;
}
input[type="radio"]{
    display: none;
}
input[type="radio"] + label:before{
    font-family: FontAwesome;
    display: inline-block;
    content:"'f10c";
    font-size: 14px;
    color: #06a3e9;
    letter-spacing: 5px;
    display: inline-block;
}
input[type="radio"]:checked + label:before{
    content:"'f192";
    font-size: 14px;
    display: inline-block;
}
    window.validate = function() {
    var valid = true;
  var checkbox1 = document.getElementById('three').checked;
  var checkbox2 = document.getElementById('four').checked;
  var checkbox3 = document.getElementById('five').checked;
  var checkbox4 = document.getElementById('six').checked;
  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == true) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }
  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex == -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }
  if ((checkbox1 || checkbox2 || checkbox3 || checkbox4) == false) {
    if (referenceToForm.elements["usrgrp[]"].selectedIndex != -1) {
      alert("Please enter all the required values");
        valid = false;
    }
  }    
    if (document.getElementById('multiple').value == -1)
    {
      alert("Please enter all the required values");
        valid = false;
    }
    if (document.getElementById('preference').value == -1)
    {
      alert("Please enter all the required values");
        valid = false;
    }
    if (valid)
    {
        document.getElementById('submit').click();
    }
}