使用JavaScript验证表单

时间:2017-12-03 21:08:58

标签: javascript html css validation

我正在开发一些JavaScript,并且我的验证还有一些问题,我需要修复它,但还没有找到它们。这必须保留在JavaScript中,遗憾的是无法通过JQuery完成。任何帮助将不胜感激。

我有以下三个问题:

电子邮件必须设置为名称最大长度为64个字符,域名为252个字符。它还需要包括标准验证实践。        我有这个集合,但它破坏了我已经设置的部分功能。

联系人复选框需要从四个中选择至少两个。

“提交”按钮需要显示错误,然后返回错误。



//Javascript


function onFocus(el) {
  if (el.value == el.defaultValue){
    el.value = '';
  }
}
function isNumber(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if ((charCode < 48 || charCode > 57))
    return false;

  return true;
}
function isAlpha(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if ((charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122))
    return false;

  return true;
}
function isAlphanum(evt) {
  var charCode = (evt.which) ? evt.which : event.keyCode
  if ((charCode < 48 || charCode > 57) && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122) && (charCode > 32))
    return false;

  return true;
}
function validate_form() {

  valid = true;

  if (document.myForm.firstname.value == "" || document.myForm.firstname.value == "abcd") {
    alert ("Please fill in the 'First Name' box.");
    valid = false;
  }
  if (document.myForm.lastname.value == "" || document.myForm.lastname.value == "abcdf") {
    alert ("Please fill in the 'Last Name' box.");
    valid = false;
  }
  if (document.myForm.address.value == "") {
    alert ("Please fill in the 'Address' box.");
    valid = false;
  }
  if (document.myForm.city.value == "") {
    alert ("Please fill in the 'City' box.");
    valid = false;
  }	
  if (document.myForm.state.selectedIndex == 0) {
    alert ("Please select your State.");
    valid = false;
  }
  if (document.myForm.zipcode.value == "") {
    alert ("Please fill in the 'Zip Code' box.");
    valid = false;
  }
  if (document.myForm.phone.value == "") {
    alert ("Please fill in the 'Area Code' box.");
    valid = false;
  }	
  if (document.myForm.phone1.value == "") {
    alert ("Please fill in the 'Phone Number' box.");
    valid = false;
  }
  if (/^\w+([\.-]?\w{ ,64})*@\w+([\.-]?\w{ ,252})*(\.\w+)+$/.test(myForm.email.value)){
    return (true)
  } else {
    alert("Please Enter a Valid Email Address!")
    return false
  }	
  if (document.myForm.conemail.value != document.myForm.email.value){
    alert ("Please Confirm E-mail.");
    valid = false;
  }
  if (( document.myForm.preference[0].checked == false ) && ( document.myForm.preference[1].checked == false ) && ( document.myForm.preference[2].checked == false )){
    alert ( "Please choose your Meal Preference" );
    valid = false;
  }
  if (( document.myForm.contact[0].checked == false ) && ( document.myForm.contact[1].checked == false ) && ( document.myForm.contact[2].checked == false ) && ( document.myForm.contact[3].checked == false ) && (document.myForm.contact.checked > 2)){
    alert ( "Please choose your Contact Method" );
    valid = false;
  }
  return valid;
}

/*function valThis() {
      var min = 1;
      var checkCont = document.getElementsByClassName('contact');
      for (var i = 0; i > checkCont.length; i++) {
        checkCont[i].onclick = function() {
          var checkCount = 0;
          for (var i = 0; i < checkCont.length; i++) {
            checkCount += (checkCont[i].checked) ?  1 : 0;
          }
         if (checkCount < min) {
          alert("Please Select Two or more Contact Methods");

          this.checked = flase;
          }
        }
      }
    }*/
/*function valEmail() {

      if (/^\w+([\.-]?\w{ ,64})*@\w+([\.-]?\w{ ,252})*(\.\w+)+$/.test(myForm.email.value)){
        return (true)
      } else {
        alert("Please Enter a Valid Email Address!")
        return false
      }	
    }*/

function mySubmit() {
  document.myForm.addEventListener( "submit", validate_form);
  document.myForm.addEventListener( "submit", valThis);
  document.myForm.addEventListener("submit", valEmail);
}
function myReset() {
  document.myForm.reset();
}
&#13;
form {
	font-family: sans-serif, serif;
	border: 3px solid black;
	padding: 10px 50px;
	max-height: 800px;
	width: 450px;
}
form input, form select{
	margin: 5px auto;
	padding: 2px;
	border: 1px solid black;
	
}
.pho {
	width: 25px;
}
.pho1 {
	width: 70px;
}
.pre1 {
	margin-left: 142px;
}
.con1 {
	margin-left: 32px;
}
#com{
	margin-top: 0px;
}
&#13;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Validation</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/project-2.js"></script>
</head>
<body>
  <form name="myForm" onSubmit = "return mySubmit()" method="post">
    <h2>Registration Form</h2>
    First Name: &ast;
    <input type="text" name="firstname" value="abcd" onfocus="onFocus(this)" onkeypress="return isAlpha(event)"><br>
    Last Name: &ast;
    <input type="text" name="lastname" value="abcdf"onfocus="onFocus(this)"  onkeypress="return isAlpha(event)"><br>
    Address: &ast;
    <input type="text" name="address" onkeypress="return isAlphanum(event)" ><br>
    City: &ast;
    <input type="text" name="city" onkeypress="return isAlpha(event)" ><br>
    State: &ast;
    <select name="state">
      <option value=""></option>
      <option value="AL">AL</option>
      <option value="AK">AK</option>
      <option value="AZ">AZ</option>
      <option value="AR">AR</option>
      <option value="CA">CA</option>
      <option value="CO">CO</option>
      <option value="CT">CT</option>
      <option value="DE">DE</option>
      <option value="FL">FL</option>
      <option value="GA">GA</option>
      <option value="HI">HI</option>
      <option value="ID">ID</option>
      <option value="IL">IL</option>
      <option value="IN">IN</option>
      <option value="IA">IA</option>
      <option value="KS">KS</option>
      <option value="KY">KY</option>
      <option value="LA">LA</option>
      <option value="ME">ME</option>
      <option value="MD">MD</option>
      <option value="MA">MA</option>
      <option value="MI">MI</option>
      <option value="MN">MN</option>
      <option value="MS">MS</option>
      <option value="MO">MO</option>
      <option value="MT">MT</option>
      <option value="NE">NE</option>
      <option value="NV">NV</option>
      <option value="NH">NH</option>
      <option value="NJ">NJ</option>
      <option value="NM">NM</option>
      <option value="NY">NY</option>
      <option value="NC">NC</option>
      <option value="ND">ND</option>
      <option value="OH">OH</option>
      <option value="OK">OK</option>
      <option value="OR">OR</option>
      <option value="PA">PA</option>
      <option value="RI">RI</option>
      <option value="SC">SC</option>
      <option value="SD">SD</option>
      <option value="TN">TN</option>
      <option value="TX">TX</option>
      <option value="UT">UT</option>
      <option value="VT">VT</option>
      <option value="VA">VA</option>
      <option value="WA">WA</option>
      <option value="WV">WV</option>
      <option value="WI">WI</option>
      <option value="WY">WY</option>
    </select><br>
    Zip Code: &ast;
    <input type="text" name="zipcode" onkeypress="return isNumber(event)" maxlength="5"><br>
    Phone: &ast;
    <input type="text" name="phone" class="pho" onkeypress="return isNumber(event)" maxlength="3">
    <input type="text" name="phone1" class="pho1" onkeypress="return isNumber(event)" maxlength="7"><br>
    <label>E-mail: &ast; </label>
    <input type="email" name="email"><br>
    Confirm E-mail: &ast;
    <input type="email" name="conemail"><br>
    <div id="pre">Meal Preference: &ast;
      <input type="radio" name="preference" class="pre" value="vegan">Vegan<br>
      <input type="radio" name="preference" class="pre1" value="vegetarian">Vegetarian<br>
      <input type="radio" name="preference" class="pre1" value="nonvegetarian">Non-Vegetarian<br></div>
    Contact Method: &ast; 
    <input type="checkbox" name="contact" class="con1" class="contact" value="phone">Phone
    <input type="checkbox" name="contact" class="contact" value="email">E-mail<br>
    (select more than one)
    <input type="checkbox" name="contact" class="contact" value="mail">Mail
    <input type="checkbox" name="contact" class="contact" value="linkedIn">LinkedIn<br>
    Comments:
    <textarea name="comments" rows="10" cols="40" maxlength="250"></textarea><br>
    <button type="submit" onclick="mySubmit()" value="Submit">Submit</button>
    <button type="reset" onclick="myReset()" value="Reset">Reset</button>
  </form>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

提交Html表单时,onSubmit attributte中声明的函数将运行以验证字段。

<form name="myForm" onSubmit = "return mySubmit()" method="post">

如果mySubmit()返回false,则由于发生错误而未提交数据。所以你需要从这个函数返回适当的布尔值。例如:

function mySubmit() {
    return valEmail() && validate_form() && valThis() && validateThat();
}

现在无法测试您的代码,但这是我能看到的。可能还有其他问题。