如何使用Javascript验证表单中的多个字段?

时间:2015-05-19 05:14:24

标签: javascript html forms validation

我正在尝试验证表单中的多个字段。

首先,我没有任何JS经验,但经过一些研究后,我已将这些代码放在一起,并且它在大多数情况下都有效。如果所有字段都留空,则弹出我的错误消息。如果我从底部开始回答表格并上升,它们也会弹出。但是,如果要验证的第一个字段中存在值,则提交整个表单。

我为极长且凌乱的代码道歉,我想我有很多方法可以缩短我的代码,但就像我说我没有太多经验。

以下是我的Javascript代码

     function validateForm() {

  var x = document.forms["myForm"]["flight_num"].value;
  var d = document.forms["myForm"]["date"].value;
  var t = document.forms["myForm"]["time"].value;
  var f = document.forms["myForm"]["friendliness"].value;
  var s = document.forms["myForm"]["storage"].value;
  var c = document.forms["myForm"]["comfort"].value;
  var cl = document.forms["myForm"]["clean"].value;
  var n = document.forms["myForm"]["noise"].value;
if (x == null || x == "") {
   document.getElementById('flighterr').innerHTML="Please enter your flight number.";

if (d == null || d == "") {
     document.getElementById('dateerr').innerHTML="Please enter the date of your flight.";

if (t == null || t == "") {
     document.getElementById('timeerr').innerHTML="Please enter the time of your flight.";

if (f == null || f == "") {
     document.getElementById('frienderr').innerHTML="Please select a choice.";

if (s == null || s == "") {
     document.getElementById('storageerr').innerHTML="Please select a choice.";

if (c == null || c == "") {
     document.getElementById('comforterr').innerHTML="Please select a choice.";

if (cl == null || cl == "") {
     document.getElementById('cleanerr').innerHTML="Please select a choice.";

if (n == null || n == "") {
     document.getElementById('noiseerr').innerHTML="Please select a choice.";
   return false; }
   return false; }
   return false; }
   return false; }
   return false; }
   return false; }
  return false;  }
    return false;}
    }

这是更新的JavaScript代码

    function validateForm() {

    var validation = [{
    field: "flight_num",
    msg: "Please enter your flight number."
        },
        {
    field: "date",
    msg: "Please enter the date of your flight."
        },
        {
    field: "time",
    msg: "Please enter the time of your flight."
        },
        {
    field: "friendliness",
    msg: "Please select a choice."
        },
        {
    field: "storage",
    msg: "Please select a choice."
       },
       {
    field: "comfort",
    msg: "Please select a choice."
       },
       {
    field: "clean",
    msg: "Please select a choice."
      },
     {
    field: "noise",
    msg: "Please select a choice."
     },
     ];

   var ok = true;

    for( var i = 0; i < validation.length; ++i ) {
        if( !document.getElementById( validation[i].field ).value ) {
     document.getElementById( validation[i].field + 'err' ).innerHTML = validation[i].msg;
    ok = false;
       }
    }

    return ok;   
        }

以下是我的html表单

   <form name="myForm"  onsubmit="return validateForm()" id="test" method="Post"  action="input.php" >
   <table>

   <tr>
   <td>First Name: </td> <td><input type="text" name="Fname" placeholder="Optional"></td>
   </tr>

   <tr>
   <td>Last Name: </td> <td><input type="text" name="Lname" placeholder="Optional"></td>
   </tr>

   <tr>
   <td>Email: </td> <td><input id="email" type="text" name="email" placeholder="Optional" ><span id="errEmail"></span></td>
   </tr>

   <tr>
   <td>Flight# </td> <td><input id="flight_num"  type="text" name="flight_num"><Span id="star">* </span><span id="flighterr"></span></td>
   </tr>

    <tr>
    <td>Date: </td><td><input id="flight_date" type="text" name="date" placeholder="YYYY-MM-DD" ><Span id="star">* </span><span id="dateerr"></span </td>
    </tr>

     <tr>
     <td>Time: </td><td><input id="time" type="text" name="time" ><Span id="star">* </span><span id="timeerr"></span></td>
     </tr>
     </table>
     </div>

     <div id="div4">
     <table id="choices">
     <tr id="rows">
     <td id="categ" rowspan="2" width="15%"><Span id="star </span>Friendliness of Staff: </td> 
     <td width="15%"><input id="friendliness" type="radio" name="friendliness" value="No opinion"></td>
     <td width="15%"><input  id="friendliness" type="radio" name="friendliness" value="Poor" ></td>
     <td width="15%"><input  id="friendliness" type="radio" name="friendliness" value="Fair" ></td>
     <td width="15%"><input   id="friendliness" type="radio" name="friendliness" value="Good" ></td>
     <td width="10%"><input  id="friendliness" type="radio" name="friendliness" value="Excellent"></td><td width="20%"><span id="frienderr"></span></td></tr>
    <tr id="rows">
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td <td>Excellent</td>
    </tr>

    <tr id="rows">
    <td id="categ" rowspan="2"><Span id="star">* </span>Space for luggage storage: </td>
    <td><input id="storage" type="radio" name="storage" value="No opinion" ></td>
    <td><input  id="storage" type="radio" name="storage" value="Poor"></td>
    <td><input  id="storage" type="radio" name="storage" value="Fair"></td>
    <td><input  id="storage" type="radio" name="storage" value="Good"></td>
    <td><input  id="storage" type="radio" name="storage" value="Excellent"></td>
    <td><span id="storageerr"></span></td> </tr>

    <tr id="rows">
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td <td>Excellent</td>
    </tr>

    <tr id="rows">
    <td id="categ" rowspan="2"><Span id="star">* </span>Comfort of seating: </td>
    <td><input id="comfort" type="radio" name="comfort" value="No opinion"></td>
    <td ><input id="comfort" type="radio" name="comfort" value="Poor"></td>
    <td><input id="comfort" type="radio" name="comfort" value="Fair"></td>
    <td><input id="comfort" type="radio" name="comfort" value="Good"></td>
    <td><input id="comfort" type="radio" name="comfort" value=" Excellent"></td>
    <td><span id="comforterr"></span></td></tr>

    <tr id="rows">
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td <td>Excellent</td </tr>

    <tr id="rows">
    <td  id="categ" rowspan="2"><Span id="star">* </span>Cleanliness of aircraft: </td>
    <td><input id="clean" type="radio" name="clean" value="No opinion" ></td>
    <td><input id="clean" type="radio" name="clean" value="Poor"></td>
    <td><input id="clean" type="radio" name="clean" Value="Fair"></td>
    <td><input id="clean" type="radio" name="clean" value="Good"></td>
    <td><input id="clean" type="radio" name="clean" Value="Excellent"></td>
    <td><span id="cleanerr"></span></td></tr>

    <tr>
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td><td>Excellent</td></tr>

    <tr id="rows">
    <td  id="categ" rowspan="2"><Span id="star">* </span>Noise level of aircraft: </td>
    <td><input id="noise" type="radio" name="noise" Value="No opinion" ></td>
    <td><input id="noise" type="radio" name="noise" Value="Poor"></td>
    <td><input id="noise" type="radio" name="noise" value="fair"></td>
    <td><input id="noise" type="radio" name="noise" value="Good"></td>
    <td><input id="noise" type="radio" name="noise" value="Excellent"></td>
    <td><span id="noiseerr"></span></td></tr>

    <tr id="rows">
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td <td>Excellent</td>
    </tr></table>

    <p><Span id="star">*  Required</span></p>

    <div id="div5">
    <table id="button">
    <tr><td><input type="submit" value="Submit"></td><td><input type="reset" value="Clear Data"></td></tr>
    </table>
    </div>
    </form> 

提前致谢。

3 个答案:

答案 0 :(得分:1)

这是我刚刚修改过您的JavaScript代码的基本验证

$('#btnsub').click(function(){
console.log("DS");
  var x = document.forms["myForm"]["flight_num"].value;
  var d = document.forms["myForm"]["date"].value;
  var t = document.forms["myForm"]["time"].value;
  var f = document.forms["myForm"]["friendliness"].value;
  var s = document.forms["myForm"]["storage"].value;
  var c = document.forms["myForm"]["comfort"].value; 
  var cl = document.forms["myForm"]["clean"].value;
  var n = document.forms["myForm"]["noise"].value;
if (x == null || x == "") {
    alert("Please enter your flight number.");  return false;}

if (d == null || d == "") {
     alert("Please enter the date of your flight.");
 return false;}
if (t == null || t == "") {
     alert("Please enter the time of your flight.");
 return false;}
if (f == null || f == "") {
     alert("Please select a choice.");
 return false;}
if (s == null || s == "") {
    alert("Please select a choice.");
 return false;}
if (c == null || c == "") {
     alert("Please select a choice.");
    return false;}
if (cl == null || cl == "") {
     alert("Please select a choice.");
 return false;}
if (n == null || n == "") {
     alert("Please select a choice.");

   return false; }

    });

这是 DEMO 页面

答案 1 :(得分:1)

嘿,我已经使用HTML 5只检查它是否正常然后接受答案 DEMO

    <form name="myForm"  onsubmit="return validateForm()" id="test" method="Post"  action="input.php" >
   <table>

   <tr>
   <td>First Name: </td> <td><input type="text" name="Fname" placeholder="Optional" required title="Enter first name"></td>
   </tr>

   <tr>
   <td>Last Name: </td> <td><input type="text" name="Lname" placeholder="Optional" required title="Enter Last name"></td>
   </tr>

   <tr>
   <td>Email: </td> <td><input id="email" type="text" name="email" placeholder="Optional" required title="Enter Email Id"><span id="errEmail" ></span></td>
   </tr>

   <tr>
   <td>Flight# </td> <td><input id="flight_num"  type="text" name="flight_num" required title="Enter Flight No."><Span id="star" >* </span><span id="flighterr"></span></td>
   </tr>

    <tr>
    <td>Date: </td><td><input id="flight_date" type="text" name="date" placeholder="YYYY-MM-DD"required title="Enter Date" ><Span id="star">* </span><span id="dateerr"></span </td>
    </tr>

     <tr>
     <td>Time: </td><td><input id="time" type="text" name="time" required title="Enter Time"><Span id="star" >* </span><span id="timeerr" ></span></td>
     </tr>
     </table>
     </div>

     <div id="div4">
     <table id="choices">
     <tr id="rows">
     <td id="categ" rowspan="2" width="15%"required><Span id="star </span>Friendliness of Staff: </td> <td width="15%"><input id="friendliness" type="radio" name="friendliness" value="No opinion"></td><td width="15%"><input  id="friendliness" type="radio" name="friendliness" value="Poor" ></td><td width="15%"><input  id="friendliness" type="radio" name="friendliness" value="Fair" ></td><td width="15%"><input   id="friendliness" type="radio" name="friendliness" value="Good" ></td><td width="10%"><input  id="friendliness" type="radio" name="friendliness" value="Excellent"></td><td width="20%"><span id="frienderr"></span></td></tr>

    <tr id="rows">
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td <td>Excellent</td>
    </tr>



     <tr id="rows">
    <td id="categ" rowspan="2" required><Span id="star">* </span>Space for luggage storage: </td><td> 
<input id="storage" type="radio" name="storage" value="No opinion" required title="Select one choice"></td><td><input  id="storage" type="radio" name="storage" value="Poor" ></td><td><input  id="storage" type="radio" name="storage" value="Fair"></td><td><input  id="storage" type="radio" name="storage" value="Good"></td><td><input  id="storage" type="radio" name="storage" value="Excellent"></td><td><span id="storageerr"></span></td> </tr>

    <tr id="rows">
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td <td>Excellent</td>
    </tr>


    <tr id="rows">
    <td id="categ" rowspan="2"><Span id="star">* </span>Comfort of seating: </td><td><input id="comfort" type="radio" name="comfort" value="No opinion  title="Select one choice"" required></td><td ><input id="comfort" type="radio" name="comfort" value="Poor"></td><td><input id="comfort" type="radio" name="comfort" value="Fair"></td><td><input id="comfort" type="radio" name="comfort" value="Good"></td><td><input id="comfort" type="radio" name="comfort" value=" Excellent"></td><td><span id="comforterr"></span></td></tr>

    <tr id="rows">
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td <td>Excellent</td </tr>


    <tr id="rows">
    <td  id="categ" rowspan="2"><Span id="star">* </span>Cleanliness of aircraft: </td><td><input id="clean" type="radio" name="clean" value="No opinion  title="Select one choice"" required ></td><td><input id="clean" type="radio" name="clean" value="Poor"></td><td><input id="clean" type="radio" name="clean" Value="Fair"></td><td><input id="clean" type="radio" name="clean" value="Good"></td><td><input id="clean" type="radio" name="clean" Value="Excellent"></td><td><span id="cleanerr"></span></td></tr>

    <tr>
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td><td>Excellent</td></tr>



    <tr id="rows">
    <td  id="categ" rowspan="2"><Span id="star">* </span>Noise level of aircraft: </td><td><input id="noise" type="radio" name="noise" Value="No opinion  title="Select one choice"" required ></td><td><input id="noise" type="radio" name="noise" Value="Poor"></td><td><input id="noise" type="radio" name="noise" value="fair"></td><td><input id="noise" type="radio" name="noise" value="Good"></td><td><input id="noise" type="radio" name="noise" value="Excellent"></td><td><span id="noiseerr"></span></td></tr>

    <tr id="rows">
    <td>No Opinion</td><td>Poor</td><td>Fair</td><td>Good</td <td>Excellent</td>
    </tr></table>


    <p><Span id="star">*  Required</span></p>

    <div id="div5">
    <table id="button">
    <tr><td><input type="submit" id="btnsub" value="Submit"></td><td><input type="reset" value="Clear Data"></td></tr>
    </table>
    </div>
    </form> 

答案 2 :(得分:-1)

只需更改逻辑validateForm()函数:

function validateForm(){
    var x = document.forms["myForm"]["flight_num"].value;
    var d = document.forms["myForm"]["date"].value;
    //......so on...//

    var IS_VALID = true; // assume form is valid
    var error_msg = '';

    if (x == NULL || x == "" || x == 'undefined') {
         IS_VALID = false;
         error_msg += "flight num can not be blank";
    }

    if (d == NULL || d == "" || d == 'undefined') {
         IS_VALID = false;
         error_msg += "\ndate can not be blank";
    }

    //......do the same for all the elment


   // finally check if the flag is true or false
    if (IS_VALID === false) {
          alert(error_msg);
    }

    return IS_VALID;
}