验证所有表单字段 - 功能无法正常工作

时间:2021-05-17 16:35:40

I created a html form and a function validateForm() to validate the form fields. However the function is only reporting issues with wrong email input, and its not validating the other fields in the form. Can you check my code to see if i have any errors.

我创建了一个html表单和一个函数validateForm()来验证表单字段。但是,该功能仅报告错误电子邮件输入的问题,并且不验证表单中的其他字段。你能检查我的代码,看看我是否有任何错误。

Thanks

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<title>Support Center</title>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/layout.css" type="text/css">
<link rel="stylesheet" href="styles/Form.css" type="text/css">
<script type="text/javascript" src="Form.js"></script>
</head>
<body>
<div class="wrapper row1">
  <header id="header" class="clear">
    <div id="hgroup">
      <h1><a href="index.html">Support Center</a></h1>
      <h2>Welcome to our website</h2>
    </div>
    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="#">Our Staff</a></li>
        <li><a href="#">Location</a></li>
        <li><a href="Form.html">Help</a></li>
        <li class="last"><a href="#"></a></li>
      </ul>
    </nav>
  </header>
</div>
</body>
<!-- content -->
<body>
      <h1>Help is here!</h1>
  <form>
        <h1>Should you need assistance, please do not hesitate to contact us:</h1>

    <div class="contentform">
        <div id="sendmessage"> Your form has been sent successfully. Thank you. </div>

        <div class="leftcontact">
                  <div class="form-group">
                    <p>Surname<span>*</span></p>
                    <span class="icon-case"><i class="fa fa-male"></i></span>
                        <input type="text" name="lastName" id="lastName"/>
                <div class="validation"></div>
       </div> 

            <div class="form-group">
            <p>First Name <span>*</span></p>
            <span class="icon-case"><i class="fa fa-user"></i></span>
                <input type="text" name="firstName" id="firstName"/>
                <div class="validation"></div>
            </div>

            <div class="form-group">
            <p>E-mail <span>*</span></p>    
            <span class="icon-case"><i class="fa fa-envelope-o"></i></span>
                <input type="email" name="emailAddress" id="emailAddress"/>
                <div class="validation"></div>
            </div>  

            <div class="form-group">
            <p>Office <span>*</span></p>
            <span class="icon-case"><i class="fa fa-location-arrow"></i></span>
                <input type="text" name="office" id="office"/>
                <div class="validation"></div>
            </div>

            <div class="form-group">
            <p>Desk <span>*</span></p>
            <span class="icon-case"><i class="fa fa-map-marker"></i></span>
                <input type="text" name="deskNumber" id="deskNumber"/>
                <div class="validation"></div>
            </div>  



    </div>

    <div class="rightcontact">  
            <div class="form-group">
            <p>Phone number <span>*</span></p>  
            <span class="icon-case"><i class="fa fa-phone"></i></span>
                <input type="text" name="mobilePhone" id="mobilePhone"/>
                <div class="validation"></div>
            </div>

            <div class="form-group">
            <p>Job Number <span>*</span></p>
            <span class="icon-case"><i class="fa fa-building-o"></i></span>
                <input type="text" name="jobNumber" id="jobNumber"/>
                <div class="validation"></div>
            </div>  

            <div class="form-group">
            <p>Computer <span>*</span></p>
            <span class="icon-case"><i class="fa fa-info"></i></span>
                <input type="text" name="computerNumber" id="computerNumber"/>
                <div class="validation"></div>
            </div>

            <div class="form-group">
            <p>Problem <span>*</span></p>   
            <span class="icon-case"><i class="fa fa-comment-o"></i></span>
                <select name="Problem">
                    <option value="New User">New User</option>
                    <option value="Delete User">Delete User</option>
                    <option value="Lost File">Lost File</option>
                    <option value="New Software Installation">New Software Installation</option>
                    <option value="Virus Checking">Virus Checking</option>
                </select>
                <div class="validation"></div>
            </div>

            <div class="form-group">
            <p>A little about your problem <span>*</span></p>
            <span class="icon-case"><i class="fa fa-comments-o"></i></span>
                <textarea name="message" rows="14"></textarea>
                <div class="validation"></div>
            </div>  
    </div>
    </div>
<button type="submit" class="bouton-contact">Send</button>

</form> 


</body>
</html>

</body>
</html>

Code

function validateForm() {
  var letters = "[A-Za-z]+$";
  var numbers = "^[0-9]+$";
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;


  var jobNumber = document.getElementById("jobNumber").value;
  var firstName = document.getElementById("firstName").value;
  var lastName = document.getElementById("lastName").value;
  var mobilePhone = document.getElementById("mobilePhone").value;
  var emailAddress = document.getElementById("emailAddress").value;
  var officeNumber = document.getElementById("office").value;
  var deskNumber = document.getElementById("deskNumber").value;
  var computerNumber = document.getElementById("computerNumber").value;


  if(jobNumber != "" && firstName != "" && lastName != "" && mobilePhone != "" && emailAddress != "" && officeNumber != "" && deskNumber != "" && computerNumber != "") {

    if(jobNumber.length == 5 && jobNumber.match(numbers)) {

      if(firstName.match(letters) && lastName.match(letters)) {

        if(mobilePhone.length == 10 && mobilePhone.match(numbers)) {

          if(emailAddress.match(emailReg)) {
            alert("Form submitted!");
            return true;
          }
          else {
            alert("Please enter a valid email");
            return false;
          }

        }
        else {
          alert("Please enter a valid mobile number");
          return false;
        }

      }
      else {
        alert("Please enter a valid first name and last name");
        return false;
      }

    }
    else {
      alert("Please enter a valid job number");
      return false;
    }

  }
  else {
    alert("Please enter in all fields");
    return false;
  }

}

2 个解决方案

#1


0  

Edit: I just noticed you're using a class contentform and I thought it was an id. I would also add an id to your form to be able to retrieve all form data with one DOM traversal instead of several. Also, the reason the email is the only one working is because the browser is validating the email without using your JS.

编辑:我刚刚注意到你正在使用类contentform,我认为它是一个id。我还要在表单中添加一个id,以便能够使用一个DOM遍历而不是几个遍历来检索所有表单数据。此外,电子邮件是唯一有效的原因是因为浏览器在不使用您的JS的情况下验证电子邮件。

First I would ditch all the variables declared and replace it with the form object.

首先,我会抛弃所有声明的变量,并将其替换为表单对象。

var formObject = document.getElementById('contentform');

Then you could check whatever child elements that are required. I would also remove the nesting of your if statements, and instead of alerting an error and returning false, add the error to an array to store each one, then return after all items are validated.

然后你可以检查所需的任何子元素。我还会删除if语句的嵌套,而不是警告错误并返回false,将错误添加到数组以存储每个错误,然后在验证所有项目后返回。

var errorList = [];
var isValid = true;
if(formObject.jobNumber == "") {
    errorList.push('Please enter a valid job number');
    isValid = false;
}

Then rinse and repeat for each element required. After that, just return the list and status (isValid).

然后冲洗并重复所需的每种元素。之后,只需返回列表和状态(isValid)。

// this should be on its own at the bottom of your function right before you return
if (!isValid) {
    alert(errorList); 
    // I would add some formatting or preferably display in the form view.
}

return isValid;


html file
// add the event handler here
<button type="submit" onclick="validateForm()" class="bouton-contact">Send</button>

Also, these

if (!isValid) {
    alert(errorList);
}

should be removed from each if statement and placed at the bottom after all have been checked.

应该从每个if语句中删除,并在检查完所有语句后放在底部。

#2


0  

Here you validate your email address: First pass the id to javascript by post method then the function validation() will works.

在这里验证您的电子邮件地址:首先通过post方法将id传递给javascript,然后函数validation()将起作用。

//html
<div>
<input type="text" name="email" id="email" class="" data-wow-delay=".5s" value="" placeholder="Email..." />
</div>
<span id="emailerror" style="display:none; color:#F00">Enter valid email id*</span>
<input  type="submit" onClick="return validation();" class="wow fadeInUp" value="Send" />

//javascript

function validation()
{
    var email = document.getElementById('email').value;
     if(email == '' || !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)))
      {
        document.getElementById('emailerror').style.display = 'inline';
         var error=1;
      }
      else
      {
      document.getElementById('emailerror').style.display = 'none';
      }

    if(error == 1)
      {
        return false;
      }
      else
      {
      return true;    
      }
    }

now your email validation works fine, thanks

现在您的电子邮件验证工作正常,谢谢

#1


0  

Edit: I just noticed you're using a class contentform and I thought it was an id. I would also add an id to your form to be able to retrieve all form data with one DOM traversal instead of several. Also, the reason the email is the only one working is because the browser is validating the email without using your JS.

编辑:我刚刚注意到你正在使用类contentform,我认为它是一个id。我还要在表单中添加一个id,以便能够使用一个DOM遍历而不是几个遍历来检索所有表单数据。此外,电子邮件是唯一有效的原因是因为浏览器在不使用您的JS的情况下验证电子邮件。

First I would ditch all the variables declared and replace it with the form object.

首先,我会抛弃所有声明的变量,并将其替换为表单对象。

var formObject = document.getElementById('contentform');

Then you could check whatever child elements that are required. I would also remove the nesting of your if statements, and instead of alerting an error and returning false, add the error to an array to store each one, then return after all items are validated.

然后你可以检查所需的任何子元素。我还会删除if语句的嵌套,而不是警告错误并返回false,将错误添加到数组以存储每个错误,然后在验证所有项目后返回。

var errorList = [];
var isValid = true;
if(formObject.jobNumber == "") {
    errorList.push('Please enter a valid job number');
    isValid = false;
}

Then rinse and repeat for each element required. After that, just return the list and status (isValid).

然后冲洗并重复所需的每种元素。之后,只需返回列表和状态(isValid)。

// this should be on its own at the bottom of your function right before you return
if (!isValid) {
    alert(errorList); 
    // I would add some formatting or preferably display in the form view.
}

return isValid;


html file
// add the event handler here
<button type="submit" onclick="validateForm()" class="bouton-contact">Send</button>

Also, these

if (!isValid) {
    alert(errorList);
}

should be removed from each if statement and placed at the bottom after all have been checked.

应该从每个if语句中删除,并在检查完所有语句后放在底部。

#2


0  

Here you validate your email address: First pass the id to javascript by post method then the function validation() will works.

在这里验证您的电子邮件地址:首先通过post方法将id传递给javascript,然后函数validation()将起作用。

//html
<div>
<input type="text" name="email" id="email" class="" data-wow-delay=".5s" value="" placeholder="Email..." />
</div>
<span id="emailerror" style="display:none; color:#F00">Enter valid email id*</span>
<input  type="submit" onClick="return validation();" class="wow fadeInUp" value="Send" />

//javascript

function validation()
{
    var email = document.getElementById('email').value;
     if(email == '' || !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)))
      {
        document.getElementById('emailerror').style.display = 'inline';
         var error=1;
      }
      else
      {
      document.getElementById('emailerror').style.display = 'none';
      }

    if(error == 1)
      {
        return false;
      }
      else
      {
      return true;    
      }
    }

now your email validation works fine, thanks

现在您的电子邮件验证工作正常,谢谢