【问题标题】:Warning messages for form validation fields are not occurring未出现表单验证字段的警告消息
【发布时间】:2019-02-08 19:35:31
【问题描述】:

我已经相应地创建了我的代码。

我最近更改了表单操作,现在表单验证警告不再适用于页面加载。例如,如果我单击提交而不在任何字段中输入数据,我会得到 0 响应并转发到不应该发生的 confirm.html 页面。

window.onload = init;
//creation of checkRegistration method
    function checkRegistration() {
        //definition of variables
        //var checkev = 0;
        var userName = document.getElementById('userName').value;
        var password = document.getElementById('password').value;
        var passwordVerify = document.getElementById('passwordVerify').value;
        var firstName = document.getElementById('firstName').value;
        var lastName = document.getElementById('lastName').value;
        var email = document.getElementById('email').value;
        var phoneNumber = document.getElementById('phoneNumber').value;
        var signUpNewsletter = document.getElementById('signUpNewsletter').value;

        var userNameError = false,
            passwordError = false,
            passwordVerifyError = false,
            firstNameError = false,
            lastNameError = false,
            emailError = false,
            phoneNumberError = false;
        
        // define logic checks
        var alphaOnly = /^[A-Za-z]+$/;
        var alphaNum = /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i;
        var phoneFormat = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
        var atrate = email.indexOf("@");
        var dot = email.lastIndexOf(".");
        
        //clearning out warniings
        document.getElementById('userNameWarning').innerHTML = "";
        document.getElementById('passwordWarning').innerHTML = "";
        document.getElementById('passwordVerifyWarning').innerHTML = "";
        document.getElementById('firstNameWarning').innerHTML = "";
        document.getElementById('lastNameWarning').innerHTML = "";
        document.getElementById('emailWarning').innerHTML = "";
        document.getElementById('phoneNumberWarning').innerHTML = "";
        
        //validation of username, first checking to see if there is no value, then checking for alphanumeric condition, else the variable checkev is incremented
        if (userName == "") {
            //passes error requiring something to be entered
            document.getElementById('userNameWarning').innerHTML = "A username is required.";
            //moves cursor to this field if error occurs
            //document.pageForm.userName.focus();
            //document.pageForm.userName.select();
            //checkev=0;
            userNameError = true;
        //ensures that username meets alphanumberic regex requirements
        } else if (!userName.match(alphaNum)) {
            document.getElementById('userNameWarning').innerHTML = "Username must contain at least one letter and one number, no special characters.";
            userNameError = true;
        //passes check with no error and increments checkev
        //else {
           // document.getElementById('userName').innerHTML = "";
            //checkev++;
        }
        
        //validation of password, first checking to see if there is no value, then checking to make sure the password is at least 8 character in lenght, else the variable checkev is incremented
        if (password == "") {
            //passes error requiring something to be entered
            document.getElementById('passwordWarning').innerHTML = "A password is required.";
            //moves cursor to this field if error occurs
            //document.pageForm.password.focus();
            //document.pageForm.password.select();
            //checkev = 0;
            passwordError = true;
        //check if password length is 8 or more characters
        } else if (password.length <= 8) {
            document.getElementById('passwordWarning').innerHTML = "A password of at least 8 characters is required.";
            passwordError = true;
        //else {
            //document.getElementById('password').innerHTML = "";
            //checkev++;
        }
        
        //validation of passwordVerify, first checking to see if there is no value, then checking to be sure that password verify matches password, inherently verifying that the password needs to be 8 characters in length, else the variable checkev is incremented
        if (passwordVerify == "" ) {
            document.getElementById('passwordVerifyWarning').innerHTML = "Please verify your password.";
            //document.pageForm.passwordVerify.focus();
            //document.pageForm.passwordVerify.select();
            //checkev = 0;
            passwordVerifyError = true;
        } else if (password != passwordVerify) {
            document.getElementById('passwordVerifyWarning').innerHTML = "Passwords do not match, password must be 8 characters.";
            passwordVerifyError = true;
        //else {
            //document.getElementById('passwordVerify').innerHTML = "";
           // checkev++;
        }
        
        //validation of first name, first checking to see if there is no value, then checking to see that the first name field is text only and no numerals, else the variable checkev is incremented
        if (firstName == "") {
          document.getElementById('firstNameWarning').innerHTML = "Your first name is required.";
            //document.pageForm.firstName.focus();
            //document.pageForm.firstName.select();
          //checkev = 0;
            firstNameError = true;
        } else if (!(firstName.match(alphaOnly))) {
            document.getElementById('firstNameWarning').innerHTML = "Please use only letters in this field.";
            firstNameError = true;
        //else {
          //document.getElementById('firstName').innerHTML = "";
          //checkev++;
        }
        
        //validation of last name, first checking to see if there is no value, then checking to see that the last name field is text only and no numerals, else the variable checkev is incremented
        if (lastName == "") {
          document.getElementById('lastNameWarning').innerHTML = "Your last name is required.";
            //document.pageForm.lastName.focus();
            //document.pageForm.lastName.select();
           // checkev = 0;
            lastNameError = true;
        } else if (!(lastName.match(alphaOnly))) {
            document.getElementById('lastNameWarning').innerHTML = "Please use only letters in this field.";
            lastNameError = true;
        //else {
         // document.getElementById('lastName').innerHTML = "";
          //checkev++;
        }
        
        //validation of email
        if (email == "") {
            document.getElementById('emailWarning').innerHTML = "Your email address is required.";
           // document.pageForm.email.focus();
           // document.pageForm.email.select();
          //checkev = 0;
            emailError = true;
        } else if (atrate < 1 || dot < atrate + 2 || dot + 2 >= email.length) {
            document.getElementById('emailWarning').innerHTML = "Your email input is not valid.";
            emailError = true;
       // else {
         // document.getElementById('email').innerHTML = "";
          //checkev++;
        }
        
        //validation of phone number, first checking to see if there is no value, then checking to see that the phonenumber should match the required phoneFormat, else the variable checkev is incremented
        if (phoneNumber == "") {
            document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required.";
            //document.pageForm.phoneNumber.focus();
            //document.pageForm.phoneNumber.select();
          //checkev = 0;
            phoneNumberError = true;
        } else  if (!(phoneNumber.match(phoneFormat))) {
            document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required in (XXX) XXX-XXXX format.";
       // else {
            //document.getElementById('phoneNumber').innerHTML = "";
           // checkev++;
            phoneNumberError = true;
        }
        
        if (userNameError === true) {
            document.getElementById('userName').focus();
            return false;

        } else if (passwordError === true) {
            document.getElementById('password').focus();
            return false;

        } else if (passwordVerifyError === true) {
            document.getElementById('passwordVerify').focus();
            return false;

        } else if (firstNameError === true) {
            document.getElementById('firstName').focus();
            return false;

        } else if (lastNameError === true) {
            document.getElementById('lastName').focus();
            return false;

        } else if (emailError === true) {
            document.getElementById('email').focus();
            return false;

        } else if (phoneNumberError === true) {
            document.getElementById('phoneNumber').focus();
            return false;

        }
        
        //validation of sign up for newsletter, checking to see if there is nothing 
}
<form id="pageForm">
        <form action="/registration.html" onsubmit=checkRegistration() method="get">
            <label for="userName">Username:</label><label2 id="userNameWarning"></label2>
            <input type="text" name="userName" id="userName" placeholder="Enter your Username" />
            <!--<span class="error" id="userName"></span><br><br>-->
            
            
            <label for="Password">Password:
            </label><label2 id="passwordWarning"></label2>
            <input type="password" name="password" placeholder="Enter your Password" />
            <!--<span class="error" id="password"></span><br><br>-->
            
            
            <label for="passwordVerify">Verify your Password:
            </label><label2 id="passwordVerifyWarning"></label2>
            <input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
            <!--<span class="error" id="passwordVerify"></span><br><br>-->
            
            
            <label for="firstName">First Name:
            </label><label2 id="firstNameWarning"></label2>
            <input type="text" name="firstName" placeholder="Enter your First Name" />
            <!--<span class="error" id="firstName"></span><br><br>-->
            
            
            <label for="hostName">Last Name:
            </label><label2 id="lastNameWarning"></label2>
            <input type="text" name="lastName" placeholder="Enter your Last Name" />
            <!--<span class="error" id="lastName"></span><br><br>-->
            
            
            <label for="email">Email:
            </label><label2 id="emailWarning"></label2>
            <input type="text" name="email" placeholder="Enter your Email Address" />
            <!--<span class="error" id="email"></span><br><br>-->
			
            
            <label for="phoneNumber">Phone Number:
            </label><label2 id="phoneNumberWarning"></label2>
            <input type="text" name="phoneNumber" placeholder="Enter your Phone Number" />
            <!--<span class="error" id="phoneNumber"></span><br><br>-->
            
            
			<label for="signUpNewsletter">Sign up for newsletter:
            </label>
            <input type="radio" name="signUpNewsletter" value="Yes" checked > Yes 
            <input type="radio" name="signUpNewsletter" value="No"> No
            <!--<br><br><span class="error" id="signUpNewsletter"></span><br><br>-->
            
            <!-- Creation of submit button-->
            <input type="submit" value="Submit" formaction=confirm.html>
 
            </form></form></body>

【问题讨论】:

  • "Uncaught ReferenceError: init is not defined"。还有为什么你有嵌套的表单标签?
  • 你用 id 注释掉了输入字段,所以你没有 id="passwordVerify"id="password" 等元素,所以 document.getElementById('password').value 将不起作用
  • 你需要onsubmit="return checkRegistration()" 然后checkRegistration 应该返回true 为ok 和false 为错误

标签: javascript html forms validation


【解决方案1】:

首先,您需要删除 window.onload = init;,因为它最初会引发错误。

其次,你的form标签嵌套在另一个form标签中,完全没必要,防止表单触发onsubmit函数,导致提交空表单错误。

最后,您的输入元素实际上没有 ID,只有名称。因此,正如 Alon 在 cmets 中所说,您的 document.getElementById('element').value 无法正常运行。

尝试使用下面的代码 sn-p 继续前进,因为它纠正了一些主要错误,因此您实际上达到了验证条件。

//creation of checkRegistration method
    function checkRegistration() {
        //definition of variables
        //var checkev = 0;
        var userName = document.getElementById('userName').value;
        var password = document.getElementById('password').value;
        var passwordVerify = document.getElementById('passwordVerify').value;
        var firstName = document.getElementById('firstName').value;
        var lastName = document.getElementById('lastName').value;
        var email = document.getElementById('email').value;
        var phoneNumber = document.getElementById('phoneNumber').value;
        var signUpNewsletter = document.getElementById('signUpNewsletter').value;

        var userNameError = false,
            passwordError = false,
            passwordVerifyError = false,
            firstNameError = false,
            lastNameError = false,
            emailError = false,
            phoneNumberError = false;
        
        // define logic checks
        var alphaOnly = /^[A-Za-z]+$/;
        var alphaNum = /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i;
        var phoneFormat = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
        var atrate = email.indexOf("@");
        var dot = email.lastIndexOf(".");
        
        //clearning out warniings
        document.getElementById('userNameWarning').innerHTML = "";
        document.getElementById('passwordWarning').innerHTML = "";
        document.getElementById('passwordVerifyWarning').innerHTML = "";
        document.getElementById('firstNameWarning').innerHTML = "";
        document.getElementById('lastNameWarning').innerHTML = "";
        document.getElementById('emailWarning').innerHTML = "";
        document.getElementById('phoneNumberWarning').innerHTML = "";
        
        //validation of username, first checking to see if there is no value, then checking for alphanumeric condition, else the variable checkev is incremented
        if (userName == "") {
            //passes error requiring something to be entered
            document.getElementById('userNameWarning').innerHTML = "A username is required.";
            //moves cursor to this field if error occurs
            //document.pageForm.userName.focus();
            //document.pageForm.userName.select();
            //checkev=0;
            userNameError = true;
        //ensures that username meets alphanumberic regex requirements
        } else if (!userName.match(alphaNum)) {
            document.getElementById('userNameWarning').innerHTML = "Username must contain at least one letter and one number, no special characters.";
            userNameError = true;
        //passes check with no error and increments checkev
        //else {
           // document.getElementById('userName').innerHTML = "";
            //checkev++;
        }
        
        //validation of password, first checking to see if there is no value, then checking to make sure the password is at least 8 character in lenght, else the variable checkev is incremented
        if (password == "") {
            //passes error requiring something to be entered
            document.getElementById('passwordWarning').innerHTML = "A password is required.";
            //moves cursor to this field if error occurs
            //document.pageForm.password.focus();
            //document.pageForm.password.select();
            //checkev = 0;
            passwordError = true;
        //check if password length is 8 or more characters
        } else if (password.length <= 8) {
            document.getElementById('passwordWarning').innerHTML = "A password of at least 8 characters is required.";
            passwordError = true;
        //else {
            //document.getElementById('password').innerHTML = "";
            //checkev++;
        }
        
        //validation of passwordVerify, first checking to see if there is no value, then checking to be sure that password verify matches password, inherently verifying that the password needs to be 8 characters in length, else the variable checkev is incremented
        if (passwordVerify == "" ) {
            document.getElementById('passwordVerifyWarning').innerHTML = "Please verify your password.";
            //document.pageForm.passwordVerify.focus();
            //document.pageForm.passwordVerify.select();
            //checkev = 0;
            passwordVerifyError = true;
        } else if (password != passwordVerify) {
            document.getElementById('passwordVerifyWarning').innerHTML = "Passwords do not match, password must be 8 characters.";
            passwordVerifyError = true;
        //else {
            //document.getElementById('passwordVerify').innerHTML = "";
           // checkev++;
        }
        
        //validation of first name, first checking to see if there is no value, then checking to see that the first name field is text only and no numerals, else the variable checkev is incremented
        if (firstName == "") {
          document.getElementById('firstNameWarning').innerHTML = "Your first name is required.";
            //document.pageForm.firstName.focus();
            //document.pageForm.firstName.select();
          //checkev = 0;
            firstNameError = true;
        } else if (!(firstName.match(alphaOnly))) {
            document.getElementById('firstNameWarning').innerHTML = "Please use only letters in this field.";
            firstNameError = true;
        //else {
          //document.getElementById('firstName').innerHTML = "";
          //checkev++;
        }
        
        //validation of last name, first checking to see if there is no value, then checking to see that the last name field is text only and no numerals, else the variable checkev is incremented
        if (lastName == "") {
          document.getElementById('lastNameWarning').innerHTML = "Your last name is required.";
            //document.pageForm.lastName.focus();
            //document.pageForm.lastName.select();
           // checkev = 0;
            lastNameError = true;
        } else if (!(lastName.match(alphaOnly))) {
            document.getElementById('lastNameWarning').innerHTML = "Please use only letters in this field.";
            lastNameError = true;
        //else {
         // document.getElementById('lastName').innerHTML = "";
          //checkev++;
        }
        
        //validation of email
        if (email == "") {
            document.getElementById('emailWarning').innerHTML = "Your email address is required.";
           // document.pageForm.email.focus();
           // document.pageForm.email.select();
          //checkev = 0;
            emailError = true;
        } else if (atrate < 1 || dot < atrate + 2 || dot + 2 >= email.length) {
            document.getElementById('emailWarning').innerHTML = "Your email input is not valid.";
            emailError = true;
       // else {
         // document.getElementById('email').innerHTML = "";
          //checkev++;
        }
        
        //validation of phone number, first checking to see if there is no value, then checking to see that the phonenumber should match the required phoneFormat, else the variable checkev is incremented
        if (phoneNumber == "") {
            document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required.";
            //document.pageForm.phoneNumber.focus();
            //document.pageForm.phoneNumber.select();
          //checkev = 0;
            phoneNumberError = true;
        } else  if (!(phoneNumber.match(phoneFormat))) {
            document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required in (XXX) XXX-XXXX format.";
       // else {
            //document.getElementById('phoneNumber').innerHTML = "";
           // checkev++;
            phoneNumberError = true;
        }
        
        if (userNameError === true) {
            document.getElementById('userName').focus();
            return false;

        } else if (passwordError === true) {
            document.getElementById('password').focus();
            return false;

        } else if (passwordVerifyError === true) {
            document.getElementById('passwordVerify').focus();
            return false;

        } else if (firstNameError === true) {
            document.getElementById('firstName').focus();
            return false;

        } else if (lastNameError === true) {
            document.getElementById('lastName').focus();
            return false;

        } else if (emailError === true) {
            document.getElementById('email').focus();
            return false;

        } else if (phoneNumberError === true) {
            document.getElementById('phoneNumber').focus();
            return false;

        }
        
        //validation of sign up for newsletter, checking to see if there is nothing 
}
<!DOCTYPE html>
<html lang="en">
        <meta charset="utf8">
    <title>tester</title>
    <body class="container">

    <form  id="pageForm" onsubmit="return checkRegistration()" action="/registration.html"  method="get">
        <label for="userName">Username:</label><label2 id="userNameWarning"></label2>
        <input type="text" name="userName" id="userName" placeholder="Enter your Username" />
        <!--<span class="error" id="userName"></span><br><br>-->
        
        
        <label for="Password">Password:
        </label><label2 id="passwordWarning"></label2>
        <input type="password" name="password"  id="password" placeholder="Enter your Password" />
        <!--<span class="error" id="password"></span><br><br>-->
        
        
        <label for="passwordVerify">Verify your Password:
        </label><label2 id="passwordVerifyWarning"></label2>
        <input type="password" name="passwordVerify"  id="passwordVerify" placeholder="Enter in your Password again" />
        <!--<span class="error" id="passwordVerify"></span><br><br>-->
        
        
        <label for="firstName">First Name:
        </label><label2 id="firstNameWarning"></label2>
        <input type="text" name="firstName" id = "firstName" placeholder="Enter your First Name" />
        <!--<span class="error" id="firstName"></span><br><br>-->
        
        
        <label for="hostName">Last Name:
        </label><label2 id="lastNameWarning"></label2>
        <input type="text" name="lastName" id= "lastName" placeholder="Enter your Last Name" />
        <!--<span class="error" id="lastName"></span><br><br>-->
        
        
        <label for="email">Email:
        </label><label2 id="emailWarning"></label2>
        <input type="text" name="email" id="email" placeholder="Enter your Email Address" />
        <!--<span class="error" id="email"></span><br><br>-->
  
        
        <label for="phoneNumber">Phone Number:
        </label><label2 id="phoneNumberWarning"></label2>
        <input type="text" name="phoneNumber" id = "phoneNumber" placeholder="Enter your Phone Number" />
        <!--<span class="error" id="phoneNumber"></span><br><br>-->
        
        
  <label for="signUpNewsletter">Sign up for newsletter:
        </label>
        <input type="radio" name="signUpNewsletter" value="Yes" checked > Yes 
        <input type="radio" name="signUpNewsletter" id="signUpNewsletter" value="No"> No
        <!--<br><br><span class="error" id="signUpNewsletter"></span><br><br>-->
        
        <!-- Creation of submit button-->
        <input type="submit" value="Submit" formaction=confirm.html>

        </form></body>

        <script src="app.js"></script>

【讨论】:

  • 嵌套表单不仅仅是不必要的;这是无效的 HTML。
  • 感谢您的帮助!我正在上基础 JavaScript 课程,并且在第三周。直到这周我都感觉很有成就感。这正如我所希望的那样运作!我现在需要更新我的 CSS 以正确格式化我的新错误传递方式。再次感谢您的帮助。
猜你喜欢
  • 2021-03-07
  • 2015-08-28
  • 2019-08-10
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多