无法使用javascript

时间:2018-02-05 13:24:43

标签: javascript html5 forms validation html-form

我正在尝试在提交之前验证表单。以下是验证限制:

  • 姓名,地址不应为空
  • 电话号码应为任意10位数字
  • 电子邮件应为有效的电子邮件地址
  • 应从下拉列表中选择一个首选项
  • 应至少选择一个爱好
  • 用户选择日期后,应显示其年龄 年和月,在输入栏旁边

如果验证中存在错误,则不应提交数据,并且错误消息应该出现在相应的输入字段旁边,并且用户输入的内容仍然可见(页面不应刷新),以便用户可以修改条目。这是我的表格。

<form name="f1" action="#" onsubmit="return validateForm()">
  <div class="container">
    <div class="row my-1">
      <div class="col-md-2">
        Name :
      </div>
      <div class="col-md-10">
        <input type="text" name="name" id="name"/>
        <span id="namevald"></span>
      </div>
    </div>
    <div class="row my-1">
      <div class="col-md-2">
        Address :
      </div>
      <div class="col-md-10">
        <textarea name="address" id="address"></textarea>
        <span id="addressvald"></span>
      </div>
    </div>
    <div class="row my-1">
      <div class="col-md-2">
        Phone :
      </div>
      <div class="col-md-10">
        <input type="tel" name="phone" id="phone"/>
        <span id="phonevald"></span>
      </div>
    </div>
    <div class="row my-1">
      <div class="col-md-2">
        Email :
      </div>
      <div class="col-md-10">
        <input type="text" name="email" id="email"/>
        <span id="emailvald"></span>
      </div>
    </div>
    <div class="row my-1">
      <div class="col-md-2">
        Preferences :
      </div>
      <div class="col-md-10">
        <select name="preferences" id="preferences">
          <option value="" selected>Select a preference..</option>
          <option value="pref1">Preference 1</option>
          <option value="pref2">Preference 2</option>
          <option value="pref3">Preference 3</option>
          <option value="pref4">Preference 4</option>
          <option value="pref5">Preference 5</option>
          <option value="pref6">Preference 6</option>
          <option value="pref7">Preference 7</option>
          <option value="pref8">Preference 8</option>
          <option value="pref9">Preference 9</option>
          <option value="pref10">Preference 10</option>
        </select>
        <span id="preferencesvald"></span>
      </div>
    </div>
    <div class="row my-1">
      <div class="col-md-2">
        Hobbies :
      </div>
      <div class="col-md-10">
        <ul>
          <li><label for="chk1"><input type="checkbox" name="chk" id="chk1">First</label></li>
          <li><label for="chk2"><input type="checkbox" name="chk" id="chk2">Second</label></li>
          <li><label for="chk3"><input type="checkbox" name="chk" id="chk3">Third</label></li>
          <li><label for="chk4"><input type="checkbox" name="chk" id="chk4">Fourth</label></li>
          <li><label for="chk5"><input type="checkbox" name="chk" id="chk5">Fifth</label></li>
        </ul>
        <span id="hobbiesvald"></span>
      </div>
    </div>
    <div class="row my-1">
      <div class="col-md-2">
        DOB :
      </div>
      <div class="col-md-10">
        <input type="date" name="date" id="date" onchange="ageCalculate()"/>
        <span id="datevald"></span>
      </div>
    </div>
    <div class="row my-1">
      <div class="col-md-12">
        <input type="submit" value="Submit.."/>
      </div>
    </div>
  </div>
</form>

这是我的javascript

function validateHobbies(){
            var chklist = document.getElementsByName('chk');
            var n = chklist.length;
            for(var i = 0; i < n; i++){
                if(chklist[i].checked) return true;
            }
            return false;
        }
        function validatePreferences(){
            var e = document.getElementByID('preferences');
            return (e.options[e.selectedIndex].value == "")? false : true;              
        }
        function validatePhone(){
            var pat = /\d+$/;
            return (pat.test(document.getElementByID('phone').value))? true : false;
        }
        function validateAddress(){
            return (document.getElementByID('address').value.trim() == "")? false : true;
        }
        function validateName(){
            return (document.getElementByID('name').value.trim() == "")? flase : true;
        }
        function validateEmail(){
            var pat = /^[a-z0-9!#$%&*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
            return (pat.test(document.getElementByID('email').value))? true : false;
        }
        function validateForm(){
            var isNameValid = validateName();
            var isAddressValid = validateAddress();
            var isPhoneValid = validatePhone();
            var isPreferencesValid = validatePreferences();
            var isHobbiesValid = validateHobbies();
            var isEmailValid = validateEmail();
            document.getElementByID('namevald').innerHTML = (isNameValid)? "" : "Name shouldn't be empty";
            document.getElementByID('addressvald').innerHTML = (isAddressValid)? "" : "Address shouldn't be empty";
            document.getElementByID('phonevald').innerHTML = (isPhoneValid)? "" : "Enter valid mobile no";
            document.getElementByID('preferencesvald').innerHTML = (isPreferencesValid)? "" : "Select a preference";
            document.getElementByID('hobbiesvald').innerHTML = (isHobbiesValid)? "" : "Select atleast 1 hobby";
            document.getElementByID('emailvald').innerHTML = (isEmailValid)? "" : "Enter a valid email";
            return (isNameValid && isAddressValid && isPhoneValid && isPreferencesValid && isHobbiesValid && isEmailValid);
        }
        function ageCalculate(){
            var dob = document.getElementByID('date').value.split("-");
            var by = parseInt(dob[0],10);
            var bm = parseInt(dob[1],10);
            var today = new Date();
            var cy = today.getFullYear();
            var cm = today.getMonth();
            var months = (cy-by)*12-bm+cm;
            document.getElementByID('datevald').innerHTML = "" + months/12 + "Years" + months%12 + "Months";
        }

验证无效。无论输入如何,表单都会提交和刷新。没有验证错误消息。我怀疑错误可能是在表单开始标记中的onsubmit属性或最后的提交类型输入,所以我尝试了event.preventDefault()和表单标记的多个其他解决方案和我的提交按钮在网上找到但似乎没有工作。究竟是什么问题?提前谢谢。

3 个答案:

答案 0 :(得分:0)

所以,首先,你的JavaScript中有一些拼写错误,即 getElementByID ,请注意这一点,它应该是 getElementById ,请注意小写D ,其次,你做了另一个拼写错误' flase ',它应该是 false 。这是我已经完成的解决方案,我实际上并未改变您实施的任何逻辑,只纠正了您对代码的一些小问题。

我个人建议,每当提交表单并在JS中执行某些操作进行测试时,请使用preventDefault()。纯粹是因为它没有提交表单,这就是为什么你看不到任何控制台错误,这是因为它会刷新页面,你可以通过网址看到,它会从(something.html)转到(something.html#)。

最后我希望这会有所帮助!

&#13;
&#13;
function validateHobbies(){
        var chklist = document.getElementsByName('chk');
        var n = chklist.length;
        for(var i = 0; i < n; i++){
            if(chklist[i].checked) return true;
        }
        return false;
    }
    function validatePreferences(){
        var e = document.getElementById('preferences');
        return (e.options[e.selectedIndex].value == "")? false : true;
    }
    function validatePhone(){
        var pat = /\d+$/;
        return (pat.test(document.getElementById('phone').value))? true : false;
    }
    function validateAddress(){
        return (document.getElementById('address').value.trim() == "")? false : true;
    }
    function validateName(){
        return (document.getElementById('name').value.trim() == "")? false : true;
    }
    function validateEmail(){
        var pat = /^[a-z0-9!#$%&*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
        return (pat.test(document.getElementById('email').value))? true : false;
    }
    function validateForm(){
        var isNameValid = validateName();
        var isAddressValid = validateAddress();
        var isPhoneValid = validatePhone();
        var isPreferencesValid = validatePreferences();
        var isHobbiesValid = validateHobbies();
        var isEmailValid = validateEmail();
        document.getElementById('namevald').innerHTML = (isNameValid)? "" : "Name shouldn't be empty";
        document.getElementById('addressvald').innerHTML = (isAddressValid)? "" : "Address shouldn't be empty";
        document.getElementById('phonevald').innerHTML = (isPhoneValid)? "" : "Enter valid mobile no";
        document.getElementById('preferencesvald').innerHTML = (isPreferencesValid)? "" : "Select a preference";
        document.getElementById('hobbiesvald').innerHTML = (isHobbiesValid)? "" : "Select atleast 1 hobby";
        document.getElementById('emailvald').innerHTML = (isEmailValid)? "" : "Enter a valid email";
        return (isNameValid && isAddressValid && isPhoneValid && isPreferencesValid && isHobbiesValid && isEmailValid);
    }
    function ageCalculate(){
        var dob = document.getElementById('date').value.split("-");
        var by = parseInt(dob[0],10);
        var bm = parseInt(dob[1],10);
        var today = new Date();
        var cy = today.getFullYear();
        var cm = today.getMonth();
        var months = (cy-by)*12-bm+cm;
        document.getElementById('datevald').innerHTML = "" + months/12 + "Years" + months%12 + "Months";
    }

    window.onload = function (){
        var frm = document.getElementById("form");
        frm.addEventListener("submit", function(e) {e.preventDefault(); validateForm();});
    };
&#13;
<form id="form" name="f1" action="#" method="POST">
      <div class="container">
          <div class="row my-1">
              <div class="col-md-2">
                  Name :
              </div>
              <div class="col-md-10">
                  <input type="text" name="name" id="name"/>
                  <span id="namevald"></span>
              </div>
          </div>
          <div class="row my-1">
              <div class="col-md-2">
                  Address :
              </div>
              <div class="col-md-10">
                  <textarea name="address" id="address"></textarea>
                  <span id="addressvald"></span>
              </div>
          </div>
          <div class="row my-1">
              <div class="col-md-2">
                  Phone :
              </div>
              <div class="col-md-10">
                  <input type="tel" name="phone" id="phone"/>
                  <span id="phonevald"></span>
              </div>
          </div>
          <div class="row my-1">
              <div class="col-md-2">
                  Email :
              </div>
              <div class="col-md-10">
                  <input type="text" name="email" id="email"/>
                  <span id="emailvald"></span>
              </div>
          </div>
          <div class="row my-1">
              <div class="col-md-2">
                  Preferences :
              </div>
              <div class="col-md-10">
                  <select name="preferences" id="preferences">
                      <option value="" selected>Select a preference..</option>
                      <option value="pref1">Preference 1</option>
                      <option value="pref2">Preference 2</option>
                      <option value="pref3">Preference 3</option>
                      <option value="pref4">Preference 4</option>
                      <option value="pref5">Preference 5</option>
                      <option value="pref6">Preference 6</option>
                      <option value="pref7">Preference 7</option>
                      <option value="pref8">Preference 8</option>
                      <option value="pref9">Preference 9</option>
                      <option value="pref10">Preference 10</option>
                  </select>
                  <span id="preferencesvald"></span>
              </div>
          </div>
          <div class="row my-1">
              <div class="col-md-2">
                  Hobbies :
              </div>
              <div class="col-md-10">
                  <ul>
                     <li><label for="chk1"><input type="checkbox" name="chk" id="chk1">First</label></li>
                     <li><label for="chk2"><input type="checkbox" name="chk" id="chk2">Second</label></li>
                     <li><label for="chk3"><input type="checkbox" name="chk" id="chk3">Third</label></li>
                     <li><label for="chk4"><input type="checkbox" name="chk" id="chk4">Fourth</label></li>
                     <li><label for="chk5"><input type="checkbox" name="chk" id="chk5">Fifth</label></li>
                  </ul>
                  <span id="hobbiesvald"></span>
              </div>
          </div>
          <div class="row my-1">
              <div class="col-md-2">
                  DOB :
              </div>
              <div class="col-md-10">
                  <input type="date" name="date" id="date" onchange="ageCalculate()"/>
                  <span id="datevald"></span>
              </div>
          </div>
          <div class="row my-1">
              <div class="col-md-12">
                  <input type="submit" value="Submit.."/>
              </div>
          </div>
      </div>
  </form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

问题在于您错误地获取了id

document.getElementByID

而不是:

document.getElementById

如果你有开发人员的工具(任何浏览器中的F12)并且正在查看控制台选项卡,你会看到错误指出这一点。当JavaScript无法运行时,请务必先检查控制台。

并且,您在false 函数中遇到了validateName的拼写错误,而您在其中编写了flase

但是,除此之外,你的整体代码比它需要的更多,它需要被带入21世纪,所以.......

首先,停止使用25年以上的内联HTML事件属性(onclickonsubmit等)技术来设置事件处理程序。有 many reasons 不使用这种不会死的古老技术。相反,请遵循现代标准,并使用.addEventListner()在JavaScript中执行所有事件处理。这意味着您将以不同的方式取消事件。

所有DOM事件处理函数都会自动传递给触发它们的事件的引用,因此应设置validateForm()函数以接收该引用,如下所示:

function validateForm(evt){

然后,在您的验证代码中,如果您知道表单无效,您将取消该事件:

evt.preventDefault();

我们可以稍微清理一下代码,而不必费心地将大多数显示错误消息的span元素放到id,只需通过代码按照元素旁边的位置访问它们。通过nextElementSibling验证。此外,我们可以通过input元素上的 getting rid of the trailing slashes 进一步清理代码,因为这也是一种古老的语法,不会给您带来任何好处,并且通常会导致错误代码。

现在,您确实在复选框旁边使用了label个元素,但它们确实应该在所有元素的旁边用于辅助功能。

最后,您计算年龄的代码比需要的更多。

我已经清理了HTML和JavaScript了,所以请看一下注释的解释:

// Get the DOM references you'll need just once:
var frm = document.querySelector("form[name='f1']")   
var dob = document.querySelector("input[type=date]"); 
var userName = document.getElementById('userName');
var address = document.getElementById('address');
var phone = document.getElementById('phone');
var email = document.getElementById('email');
var preferences = document.getElementById('preferences');
var hobbies = document.getElementById('hobbiesvald');
var dateValid = document.getElementById('datevald');

// We will want to loop over these later and to be sure the .forEach loop
// works in all browsers, we convert the node list into an Array
var errorMessages = Array.prototype.slice.call(document.querySelectorAll(".error"));

// Set up event handlers:
frm.addEventListener("submit", validateForm); 
dob.addEventListener("change", ageCalculate);

// You really don't need separate functions to validate each form field given
// how simple those validations were:
function validateForm(evt){
  // Reset all error messages:
  errorMessages.forEach(function(msg){
    msg.textContent = "";
  });
  hobbies.textContent = "";

  var valid = true;  // Assume that everything is valid to start with
  
  if(userName.value.trim() === ""){
    // Since the error message should appear in the next element that comes after
    // the form field, we can reference it with: nextElementSibling
    userName.nextElementSibling.textContent = "Name shouldn't be empty";
    valid = false;
  }
  
  if(address.value.trim() === ""){
    address.nextElementSibling.textContent = "Address shouldn't be empty";
    valid = false;
  }
  
  if(!/\d+$/.test(phone.value)){
    phone.nextElementSibling.textContent = "Enter valid mobile no";
    valid = false;  
  }

  var pat = /^[a-z0-9!#$%&*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;

  if(!pat.test(email.value)){
    email.nextElementSibling.textContent = "Enter a valid email";
    valid = false;    
  }  
  
  if(preferences.value === ""){
    preferences.nextElementSibling.textContent = "Select a preference";
    valid = false;  
  }
  
  // Just get the checked checkboxes
  var chklist = document.querySelectorAll('input[type=checkbox]:checked');    
  
  // And if none were found, validation fails  
  if (chklist.length === 0){
   hobbies.textContent = "Select atleast 1 hobby";
   valid = false;
  }  

  // If any of the tests failed, cancel the submit
  if(!valid){ evt.preventDefault(); }
}

function ageCalculate(evt){
  if(this.value){
    var ddif = new Date(new Date() - new Date(this.value));
    var message = 
      (ddif.toISOString().slice(0, 4) - 1970) + " Years " + 
      (ddif.getMonth()+1) + " Months " + ddif.getDate() + " Days old";
  
    dateValid.textContent = message;
  } else {
    dateValid.textContent = "";
  }
}
.error { color:red; font-weight:bold; }
<form name="f1" action="#">            
  <div class="container">
    <div class="row my-1">
      <div class="col-md-2"><label for="userName">Name :</label></div>
        <div class="col-md-10">
           <input type="text" name="userName" id="userName"><span class="error"></span>
         </div>
      </div>
      <div class="row my-1">
        <div class="col-md-2"><label for="address">Address :</label></div>
        <div class="col-md-10">
          <textarea name="address" id="address"></textarea><span class="error"></span>
        </div>
        </div>
        <div class="row my-1">
          <div class="col-md-2"><label for="phone">Phone :</label>
        </div>
        <div class="col-md-10">
          <input type="tel" name="phone" id="phone"><span class="error"></span>
        </div>
      </div>
      <div class="row my-1">
        <div class="col-md-2"><label for="email">Email :</label></div>
        <div class="col-md-10">
          <input type="text" name="email" id="email"><span class="error"></span>
        </div>
      </div>
      <div class="row my-1">
        <div class="col-md-2"><label for="preferences">Preferences :</label></div>
        <div class="col-md-10">
          <select name="preferences" id="preferences">
            <option value="" selected>Select a preference..</option>
            <option value="pref1">Preference 1</option>
            <option value="pref2">Preference 2</option>
            <option value="pref3">Preference 3</option>
            <option value="pref4">Preference 4</option>
            <option value="pref5">Preference 5</option>
            <option value="pref6">Preference 6</option>
            <option value="pref7">Preference 7</option>
            <option value="pref8">Preference 8</option>
            <option value="pref9">Preference 9</option>
            <option value="pref10">Preference 10</option>
          </select><span  class="error"></span>
        </div>
      </div>
      <div class="row my-1">
        <div class="col-md-2">Hobbies :</div>
           <div class="col-md-10">
              <ul>
                <li><label for="chk1"><input type="checkbox" name="chk" id="chk1">First</label></li>
                <li><label for="chk2"><input type="checkbox" name="chk" id="chk2">Second</label></li>
                <li><label for="chk3"><input type="checkbox" name="chk" id="chk3">Third</label></li>
                <li><label for="chk4"><input type="checkbox" name="chk" id="chk4">Fourth</label></li>
                <li><label for="chk5"><input type="checkbox" name="chk" id="chk5">Fifth</label></li>
              </ul>
              <span id="hobbiesvald" class="error"></span>
            </div>
          </div>
          <div class="row my-1">
             <div class="col-md-2"><label for="date">DOB :</label></div>
              <div class="col-md-10">
                <input type="date" name="date" id="date"><span id="datevald"></span>
              </div>
            </div>
            <div class="row my-1">
              <div class="col-md-12">
                <input type="submit" value="Submit..">
              </div>
            </div>
        </div>
    </form>

答案 2 :(得分:-2)

您可以使用HTML5验证表单。只需添加输入标记所需。对于电子邮件验证,您必须使用“email”作为值添加type属性。

<input type="email" name="email" required />