簡體   English   中英

正則表達式不起作用-在線表單驗證和提交

[英]Regular Expression not working - Online form validation and submission

所以我在表格方面遇到了麻煩。 設置了多種驗證技術。 我最明顯的兩個問題是一個警報,該警報在程序啟動時彈出,但僅在激活onblur()並且我的update()函數返回錯誤值時才彈出。 而且,我的正則表達式堅持要求在對字符串進行測試時為我提供錯誤的條件。 完成的表格應驗證各種信息並更新放置在費用輸入中的值。 真的卡在這個...

 window.onload = initPage; /*initPage() Initializes the contents of the Web page */ function initPage() { //declare array variable dataFields points to input elements from the expenseEntry class var dataFields = new Array(); var allElems = document.getElementsByTagName("*"); for( var i = 0; i < allElems.length; i ++) { if(allElems[i].className == "expenseEntry") dataFields.push(allElems[i]); } //add onblur event that runs update() function whenever focus leaves a datafield. for(var i = 0; i < dataFields.length; i++) { dataFields[i].onblur = update(); } //event handler that runs validateForm() upon submitting the form. document.forms[0].onsubmit = validateForm; } /* testLength() Tests a field for its length. */ function testLength(field) { if (field.value.length == 0) { // Change the background color to white or yellow depending on the lenght. field.style.backgroundColor = "yellow"; return false; } else field.style.backgroundColor = "white"; return true; } /* testPattern() Tests a field for its pattern. */ function testPattern(field, regx) { if (regx.test(field)) { field.style.backgroundColor = "white"; field.style.color = "black"; return true; } else field.style.backgroundColor = "yellow"; field.style.color = "red"; return false; } /* validateForm() Validates a Web form */ function validateForm() { var isValid = true; //testLength function with lname field also for fname, address, and summary to make sure an entry has been made. if (testLength(document.forms[0].lname) == false) { isValid = false;} if (testLength(document.forms[0].fname) == false) { isValid = false;} if (testLength(document.forms[0].address) == false) { isValid = false;} if (testLength(document.forms[0].summary) == false) { isValid = false;} //must match ACT followed by six digits if (testPattern(document.forms[0].account,/^ACT\\d{6}$/) == false) {isValid = false;} //dept field. regx should match DEPT followed by three digits if (testPattern(document.forms[0].department.value,/^DEPT\\d{3}$/) == false) {isValid = false;} //Project field with regx should match PROJ followed by five digits if (testPattern(document.forms[0].project,/^PROJ\\d{5}$/) == false) {isValid = false;} //call testPattern function to test SSN. match 9 digits or text string if (testPattern(document.forms[0].ssn,/^\\d{3}-\\d{2}-\\d{4}$/) == false) {isValid = false;} if (isValid == false) {alert("Please fill out all required fields in the proper format.");} return isValid; } /* calcRow Calculates the costs within one row of the travel report */ function calcRow(row) { var travel = parseFloat(document.forms[0].elements["travel"+row].value); var lodge = parseFloat(document.forms[0].elements["lodge"+row].value); var meal = parseFloat(document.forms[0].elements["meal"+row].value); return travel+lodge+meal; } /* calcTotal() Calculates the total cost of the travel */ function calcTotal() { //create a variable totalEXP var totalExp = 0; //create a for loop that runs 1 t0 4 for (var i = 1; i <= 4; i++) // increase the value of totalExp by value returned for calcRow { totalExp += calcRow(i);} return totalExp; } /* upDate() Updates the total travel cost */ function update() { //create a variable numRegExp var numRegExp = /^\\d*(\\.\\d{0,2})?$/; // Test weather the currently selected object matches the numRegExp pattern if (numRegExp.test(this.value)){ // Display the value of the current object to 2 decimal places. parseInt(this.value).toFixed(2); //insert a for loop that runs 1 to 4 for all the expense rows in the form for (var i = 1; i < 4; i++) { //Set the value of sub[i] field to the value returned by calcRow() document.forms[0].elements["sub" + i].value = calcRow(i).toFixed(2); //set the value of the total field equal to the value returned by the calTotal() function document.forms[0].total.value = calcTotal().toFixed(2); } } //if the condition is not met display alert and change value. else if (numRegExp.test(this.value) == false) { alert("Invalid currency value"); (this.value = "0.00"); this.focus(); } } 
 body {background: white url(back.jpg) repeat-y scroll 0px 0px} #links {position: absolute; top: 10px; left: 0px} #main {border: 1px solid black; width: 640px; padding: 5px; background-color: white; margin-left: 100px; margin-top: 0px} span {color: red; font-family: Arial, Helvetica, sans-serif; font-size: 9pt} table {font-size: 8pt; width: 630px; margin-top: 5px; margin-bottom: 0px} th {background-color: rgb(153,204,255); text-align: left; font-weight: normal; font-family: Arial, Helvetica, sans-serif} #reporttitle {background-color: white; text-align: center; font-family: Arial, Helvetica, sans-serif; font-size: 18pt; color: rgb(153,204,255); font-weight: bold} input {width: 100%; font-size: 8pt} select {width: 100%; font-size: 8pt} #lname, #fname {width: 150px} #account, #department, #project {width: 150px} #traveltable th {text-align: center} #subhead {width: 100px} #travelexphead, #lodgeexphead, #mealexphead {width: 80px} #date1, #date2, #date3, #date4 {text-align: center} #travel1, #travel2, #travel3, #travel4 {text-align: right} #lodge1, #lodge2, #lodge3, #lodge4 {text-align: right} #meal1, #meal2, #meal3, #meal4 {text-align: right} #sub1, #sub2, #sub3, #sub4,#total {text-align: right} #traveltable #totalhead {text-align: right} textarea {height: 100px; width: 100%} #main #psub {text-align: center} #main p input {width: 190px; background-color: rgb(153,204,255); color: black; letter-spacing: 5} 
 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- New Perspectives on JavaScript, 2nd Edition Tutorial 5 Case Problem 2 Expense Report Form Author: Gavin Macken Date: 8 March `15 Filename: exp.htm Supporting files: back.jpg, exp.css, links.jpg, logo.jpg, report.js --> <title>Expense Report</title> <link href="exp.css" rel="stylesheet" type="text/css" /> <script src = "report.js" type = "text/javascript"></script> </head> <body> <form id="expform" method="post" action="done.htm"> <div id="links"><img src="links.jpg" alt="" /></div> <div id="main"> <p><img src="logo.jpg" alt="DeLong Enterprises" /></p> <table cellspacing="2"> <tr> <th colspan="5" id="reporttitle">Travel Expense Report</th> </tr> <tr> <th>Name (Last)<span>*</span></th> <th>(First)<span>*</span></th> <th>(Initial)</th> <th>Account<span>*</span></th> <td><input name="account" id="account" /></td> </tr> <tr> <td><input name="lname" id="lname"/></td> <td><input name="fname" id="fname"/></td> <td><input name="init" id="init"/></td> <th>Department<span>*</span></th> <td><input name="department" id="department" /></td> </tr> <tr> <th>Social Security Number<span>*</span></th> <td colspan="2"><input name="ssn" id="ssn" /></td> <th>Project<span>*</span></th> <td><input name="project" id="project" /></td> </tr> </table> <table cellspacing="2"> <tr> <th>Send Check to:<span>*</span></th> <th>Trip Summary<span>*</span></th> </tr> <tr> <td> <textarea id="address" name="address" rows="" cols=""></textarea> </td> <td> <textarea id="summary" name="summary" rows="" cols=""></textarea> </td> </tr> </table> <table id="traveltable" cellspacing="2"> <tr> <th id="datehead">Travel Date</th> <th id="travelexphead">Travel Cost</th> <th id="traveltypehead">Type</th> <th id="lodgeexphead">Lodging</th> <th id="mealexphead">Meals</th> <th id="subhead">Total</th> </tr> <tr> <td><input name="date1" id="date1" /></td> <td><input name="travel1" id="travel1" value="0.00" class="expenseEntry" /></td> <td><select name="traveltype1" id="traveltype1"> <option>air</option> <option>auto</option> <option>taxi</option> <option>train</option> </select> </td> <td><input name="lodge1" id="lodge1" value="0.00" class="expenseEntry" /></td> <td><input name="meal1" id="meal1" value="0.00" class="expenseEntry" /></td> <td><input name="sub1" id="sub1" value="0.00" readonly="readonly" /></td> </tr> <tr> <td><input name="date2" id="date2" /></td> <td><input name="travel2" id="travel2" value="0.00" class="expenseEntry" /></td> <td><select name="traveltype2" id="traveltype2"> <option>air</option> <option>auto</option> <option>taxi</option> <option>train</option> </select> </td> <td><input name="lodge2" id="lodge2" value="0.00" class="expenseEntry" /></td> <td><input name="meal2" id="meal2" value="0.00" class="expenseEntry" /></td> <td><input name="sub2" id="sub2" value="0.00" readonly="readonly" /></td> </tr> <tr> <td><input name="date3" id="date3" /></td> <td><input name="travel3" id="travel3" value="0.00" class="expenseEntry" /></td> <td><select name="traveltype3" id="traveltype3"> <option>air</option> <option>auto</option> <option>taxi</option> <option>train</option> </select> </td> <td><input name="lodge3" id="lodge3" value="0.00" class="expenseEntry" /></td> <td><input name="meal3" id="meal3" value="0.00" class="expenseEntry" /></td> <td><input name="sub3" id="sub3" value="0.00" readonly="readonly" /></td> </tr> <tr> <td><input name="date4" id="date4" /></td> <td><input name="travel4" id="travel4" value="0.00" class="expenseEntry" /></td> <td><select name="traveltype4" id="traveltype4"> <option>air</option> <option>auto</option> <option>taxi</option> <option>train</option> </select> </td> <td><input name="lodge4" id="lodge4" value="0.00" class="expenseEntry" /></td> <td><input name="meal4" id="meal4" value="0.00" class="expenseEntry" /></td> <td><input name="sub4" id="sub4" value="0.00" readonly="readonly" /></td> </tr> <tr> <th colspan="5" id="totalhead">TOTAL</th> <td><input id="total" name="total" readonly="readonly" value="0.00" /></td> </tr> <tr> <td colspan="6"><span>* - Indicates a required field</span></td> </tr> </table> <p id="psub"> <input type="submit" value="Submit Report" /> </p> </div> </form> </body> </html> 

您正在針對regexp測試DOM元素,這沒有任何意義。 regx.test()的參數必須是字符串。 您需要使用該字段的值:

if (regx.test(field.value)) {

您將onblur屬性設置為錯誤。 應該將其設置為update函數,但是您當時正在調用該函數。 它應該是:

dataFields[i].onblur = update;

當您為department字段調用testPattern時,您正在使用.value屬性。 但是testPattern期望參數是元素,而不是值。 它應該是:

if (testPattern(document.forms[0].department, /^DEPT\d{3}$/) == false)

 window.onload = initPage; /*initPage() Initializes the contents of the Web page */ function initPage() { //declare array variable dataFields points to input elements from the expenseEntry class var dataFields = new Array(); var allElems = document.getElementsByTagName("*"); for (var i = 0; i < allElems.length; i++) { if (allElems[i].className == "expenseEntry") dataFields.push(allElems[i]); } //add onblur event that runs update() function whenever focus leaves a datafield. for (var i = 0; i < dataFields.length; i++) { dataFields[i].onblur = update; } //event handler that runs validateForm() upon submitting the form. document.forms[0].onsubmit = validateForm; } /* testLength() Tests a field for its length. */ function testLength(field) { if (field.value.length == 0) { // Change the background color to white or yellow depending on the lenght. field.style.backgroundColor = "yellow"; return false; } else field.style.backgroundColor = "white"; return true; } /* testPattern() Tests a field for its pattern. */ function testPattern(field, regx) { if (regx.test(field.value)) { field.style.backgroundColor = "white"; field.style.color = "black"; return true; } else field.style.backgroundColor = "yellow"; field.style.color = "red"; return false; } /* validateForm() Validates a Web form */ function validateForm() { var isValid = true; //testLength function with lname field also for fname, address, and summary to make sure an entry has been made. if (testLength(document.forms[0].lname) == false) { isValid = false; } if (testLength(document.forms[0].fname) == false) { isValid = false; } if (testLength(document.forms[0].address) == false) { isValid = false; } if (testLength(document.forms[0].summary) == false) { isValid = false; } //must match ACT followed by six digits if (testPattern(document.forms[0].account, /^ACT\\d{6}$/) == false) { isValid = false; } //dept field. regx should match DEPT followed by three digits if (testPattern(document.forms[0].department, /^DEPT\\d{3}$/) == false) { isValid = false; } //Project field with regx should match PROJ followed by five digits if (testPattern(document.forms[0].project, /^PROJ\\d{5}$/) == false) { isValid = false; } //call testPattern function to test SSN. match 9 digits or text string if (testPattern(document.forms[0].ssn, /^\\d{3}-\\d{2}-\\d{4}$/) == false) { isValid = false; } if (isValid == false) { alert("Please fill out all required fields in the proper format."); } return isValid; } /* calcRow Calculates the costs within one row of the travel report */ function calcRow(row) { var travel = parseFloat(document.forms[0].elements["travel" + row].value); var lodge = parseFloat(document.forms[0].elements["lodge" + row].value); var meal = parseFloat(document.forms[0].elements["meal" + row].value); return travel + lodge + meal; } /* calcTotal() Calculates the total cost of the travel */ function calcTotal() { //create a variable totalEXP var totalExp = 0; //create a for loop that runs 1 t0 4 for (var i = 1; i <= 4; i++) // increase the value of totalExp by value returned for calcRow { totalExp += calcRow(i); } return totalExp; } /* upDate() Updates the total travel cost */ function update() { //create a variable numRegExp var numRegExp = /^\\d*(\\.\\d{0,2})?$/; // Test weather the currently selected object matches the numRegExp pattern if (numRegExp.test(this.value)) { // Display the value of the current object to 2 decimal places. parseInt(this.value).toFixed(2); //insert a for loop that runs 1 to 4 for all the expense rows in the form for (var i = 1; i < 4; i++) { //Set the value of sub[i] field to the value returned by calcRow() document.forms[0].elements["sub" + i].value = calcRow(i).toFixed(2); //set the value of the total field equal to the value returned by the calTotal() function document.forms[0].total.value = calcTotal().toFixed(2); } } //if the condition is not met display alert and change value. else if (numRegExp.test(this.value) == false) { alert("Invalid currency value"); (this.value = "0.00"); this.focus(); } } 
 body { background: white url(back.jpg) repeat-y scroll 0px 0px } #links { position: absolute; top: 10px; left: 0px } #main { border: 1px solid black; width: 640px; padding: 5px; background-color: white; margin-left: 100px; margin-top: 0px } span { color: red; font-family: Arial, Helvetica, sans-serif; font-size: 9pt } table { font-size: 8pt; width: 630px; margin-top: 5px; margin-bottom: 0px } th { background-color: rgb(153, 204, 255); text-align: left; font-weight: normal; font-family: Arial, Helvetica, sans-serif } #reporttitle { background-color: white; text-align: center; font-family: Arial, Helvetica, sans-serif; font-size: 18pt; color: rgb(153, 204, 255); font-weight: bold } input { width: 100%; font-size: 8pt } select { width: 100%; font-size: 8pt } #lname, #fname { width: 150px } #account, #department, #project { width: 150px } #traveltable th { text-align: center } #subhead { width: 100px } #travelexphead, #lodgeexphead, #mealexphead { width: 80px } #date1, #date2, #date3, #date4 { text-align: center } #travel1, #travel2, #travel3, #travel4 { text-align: right } #lodge1, #lodge2, #lodge3, #lodge4 { text-align: right } #meal1, #meal2, #meal3, #meal4 { text-align: right } #sub1, #sub2, #sub3, #sub4, #total { text-align: right } #traveltable #totalhead { text-align: right } textarea { height: 100px; width: 100% } #main #psub { text-align: center } #main p input { width: 190px; background-color: rgb(153, 204, 255); color: black; letter-spacing: 5 } 
 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- New Perspectives on JavaScript, 2nd Edition Tutorial 5 Case Problem 2 Expense Report Form Author: Gavin Macken Date: 8 March `15 Filename: exp.htm Supporting files: back.jpg, exp.css, links.jpg, logo.jpg, report.js --> <title>Expense Report</title> <link href="exp.css" rel="stylesheet" type="text/css" /> <script src="report.js" type="text/javascript"></script> </head> <body> <form id="expform" method="post" action="done.htm"> <div id="links"> <img src="links.jpg" alt="" /> </div> <div id="main"> <p> <img src="logo.jpg" alt="DeLong Enterprises" /> </p> <table cellspacing="2"> <tr> <th colspan="5" id="reporttitle">Travel Expense Report</th> </tr> <tr> <th>Name (Last)<span>*</span> </th> <th>(First)<span>*</span> </th> <th>(Initial)</th> <th>Account<span>*</span> </th> <td> <input name="account" id="account" /> </td> </tr> <tr> <td> <input name="lname" id="lname" /> </td> <td> <input name="fname" id="fname" /> </td> <td> <input name="init" id="init" /> </td> <th>Department<span>*</span> </th> <td> <input name="department" id="department" /> </td> </tr> <tr> <th>Social Security Number<span>*</span> </th> <td colspan="2"> <input name="ssn" id="ssn" /> </td> <th>Project<span>*</span> </th> <td> <input name="project" id="project" /> </td> </tr> </table> <table cellspacing="2"> <tr> <th>Send Check to:<span>*</span> </th> <th>Trip Summary<span>*</span> </th> </tr> <tr> <td> <textarea id="address" name="address" rows="" cols=""></textarea> </td> <td> <textarea id="summary" name="summary" rows="" cols=""></textarea> </td> </tr> </table> <table id="traveltable" cellspacing="2"> <tr> <th id="datehead">Travel Date</th> <th id="travelexphead">Travel Cost</th> <th id="traveltypehead">Type</th> <th id="lodgeexphead">Lodging</th> <th id="mealexphead">Meals</th> <th id="subhead">Total</th> </tr> <tr> <td> <input name="date1" id="date1" /> </td> <td> <input name="travel1" id="travel1" value="0.00" class="expenseEntry" /> </td> <td> <select name="traveltype1" id="traveltype1"> <option>air</option> <option>auto</option> <option>taxi</option> <option>train</option> </select> </td> <td> <input name="lodge1" id="lodge1" value="0.00" class="expenseEntry" /> </td> <td> <input name="meal1" id="meal1" value="0.00" class="expenseEntry" /> </td> <td> <input name="sub1" id="sub1" value="0.00" readonly="readonly" /> </td> </tr> <tr> <td> <input name="date2" id="date2" /> </td> <td> <input name="travel2" id="travel2" value="0.00" class="expenseEntry" /> </td> <td> <select name="traveltype2" id="traveltype2"> <option>air</option> <option>auto</option> <option>taxi</option> <option>train</option> </select> </td> <td> <input name="lodge2" id="lodge2" value="0.00" class="expenseEntry" /> </td> <td> <input name="meal2" id="meal2" value="0.00" class="expenseEntry" /> </td> <td> <input name="sub2" id="sub2" value="0.00" readonly="readonly" /> </td> </tr> <tr> <td> <input name="date3" id="date3" /> </td> <td> <input name="travel3" id="travel3" value="0.00" class="expenseEntry" /> </td> <td> <select name="traveltype3" id="traveltype3"> <option>air</option> <option>auto</option> <option>taxi</option> <option>train</option> </select> </td> <td> <input name="lodge3" id="lodge3" value="0.00" class="expenseEntry" /> </td> <td> <input name="meal3" id="meal3" value="0.00" class="expenseEntry" /> </td> <td> <input name="sub3" id="sub3" value="0.00" readonly="readonly" /> </td> </tr> <tr> <td> <input name="date4" id="date4" /> </td> <td> <input name="travel4" id="travel4" value="0.00" class="expenseEntry" /> </td> <td> <select name="traveltype4" id="traveltype4"> <option>air</option> <option>auto</option> <option>taxi</option> <option>train</option> </select> </td> <td> <input name="lodge4" id="lodge4" value="0.00" class="expenseEntry" /> </td> <td> <input name="meal4" id="meal4" value="0.00" class="expenseEntry" /> </td> <td> <input name="sub4" id="sub4" value="0.00" readonly="readonly" /> </td> </tr> <tr> <th colspan="5" id="totalhead">TOTAL</th> <td> <input id="total" name="total" readonly="readonly" value="0.00" /> </td> </tr> <tr> <td colspan="6"><span>* - Indicates a required field</span> </td> </tr> </table> <p id="psub"> <input type="submit" value="Submit Report" /> </p> </div> </form> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM