Salve volevo aggiungere il controllo errori su un mio form e ho trovato questa guida:
http://javascript.html.it/articoli/l...on-javascript/
son riuscito a implementarlo usando il secondo metodo (quello con le classi) negli input di testo però non so come fare per i dropdown box e i radio button, qualcuno mi può aiutare?
il codice ve lo copio qui sotto, potete anche scaricarlo da quel link sopra
default.htm
validate.jscodice:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Javascript Form</title> <script type="text/javascript" src="validate.js"></script> <script type="text/javascript" src="submitvalidate.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="formstyle.css" title="default" /> </head> <body> <fieldset> <legend>Form</legend> <form name="form1" id="form1" method="post" action="#" > <table width="555"> <tr> <td width="186">Nome </td> <td width="146"><input type="text" name="name" tabindex="1" id="name" class="validate required name namemsg"/></td> <td width="207" class="rules" id ="namemsg">Required</td> </tr> <tr> <td width="186">Orario</td> <td width="146"><select name="orario" id="orario" class="validate required orario orariomsg"/> <option> -- Seleziona --</option> <option value="indifferente" > indifferente</option> <option value="mattina" > mattina</option> <option value="pranzo" > pranzo</option> <option value="pomeriggio" > pomeriggio</option> <option value="sera" > sera</option> </select></td> <td width="207" class="rules" id ="orariomsg">Required</td> </tr> <tr> <td width="186">Sesso </td> <td width="146"><input type="radio" name="sex" value="male" /> M <input type="radio" name="sex" value="female" /> F</td> <td width="207" class="rules" id ="sexmsg">Required</td> </tr> <tr> <td>Zipcode </td> <td><input type="text" name="nick" tabindex="2" id="nick" class="validate notrequired zip nickmsg"/></td> <td id="nickmsg" class="rules"></td> </tr> <tr> <td>Email </td> <td><input type="text" name="email" tabindex="2" id="email" class="validate required email emailmsg"/></td> <td id="emailmsg" class="rules">Required</td> </tr> <tr> <td></td> <td></td> <td><input type="submit" name="Submit" value="Submit" tabindex="9" /> </td> </tr> </table> </form> </fieldset> </body> </html>
submitvalidate.jscodice://Created By: Chris Campbell //www.particletree.com window.onload = attachFormHandlers; function attachFormHandlers() { var form = document.getElementById('form1') // get the form if (document.getElementsByTagName)//make sure were on a newer browser { var objInput = document.getElementsByTagName('input'); // store all input fields for (var iCounter=0; iCounter<objInput.length; iCounter++) objInput[iCounter].onchange = function(){return attach(this);} //attach the onchange to each input field } form.onsubmit = function(){return validate();} //attach validate() to the form } var gContinue = true; function attach(objInput) { sVal = objInput.value; //get value inside of input field var sFeedBack; //feedback is the feedback message sent back to the user gContinue = true; sRules = objInput.className.split(' '); // get all the rules from the input box classname sValidate = sRules[0]; //validate means we will validate the field sRequired = sRules[1]; // required means field is required sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date) sFeedbackLoc = sRules[3]; //feedbackLoc is the td id where feedback is sent to. sFeedback = validateRequired (sRequired, sVal, sTypeCheck); //validateRequired() checks if it is required and then sends back feedback if (gContinue) //if it is required and blank gContinue is false and we don't validate anymore. // this is done because if it is blank //it will also fail other tests. We don't want to spam the user with INVALID EMAIL!! if the field is still blank. { // check the different validation cases (ie: email, phone, etc.) switch (sTypeCheck) { case "date": sFeedback = validateDate(sVal); break; case "email": sFeedback = validateEmail(sVal); break; case "phone": sFeedback = validatePhone(sVal); break; case "zip": sFeedback = validateZip(sVal); break; case "password": sFeedback = validatePassword(sVal); break; case "name": sFeedback = validateName(sVal); break; case "numeric": sFeedback = validateNumeric(sVal); break; } } // after validation is complete return the feedback document.getElementById(sFeedbackLoc).innerHTML = sFeedback; } function validateRequired(sRequired, sVal, sTypecheck) { if (sRequired == "required") //check if required if not, continue validation script { if (sVal == "") //if it is rquired and blank then it is an error and continues to be required { gContinue = false; return "Required"; } else if (sTypecheck == "none") //if its not blank and has no other validation requirements the field passes { return "Thank You"; } } } function validateDate(sVal) { // our date regular expression (http://www.regexlib.com) var regex=/(((0[13578]|10|12)([-.\/])(0[1-9]|[12][0-9]|3[01])([-.\/])(\d{4}))|((0[469]|11)([-.\/])([0][1-9]|[12][0-9]|30)([-.\/])(\d{4}))|((2)([-.\/])(0[1-9]|1[0-9]|2[0-8])([-.\/])(\d{4}))|((2)(\.|-|\/)(29)([-.\/])([02468][048]00))|((2)([-.\/])(29)([-.\/])([13579][26]00))|((2)([-.\/])(29)([-.\/])([0-9][0-9][0][48]))|((2)([-.\/])(29)([-.\/])([0-9][0-9][2468][048]))|((2)([-.\/])(29)([-.\/])([0-9][0-9][13579][26])))/; // do the comparison, if we have a match write thank you or else the date is invalid if (regex.test(sVal)) { return "Thank You"; } else { return "Invalid Date"; } } function validateEmail(sVal) { // our email regular expression (http://www.regexlib.com) var regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/; // do the comparison, if we have a match write thank you or else the email is invalid if (regex.test(sVal)) { return "Thank You"; } else { return "Invalid Email Address"; } } function validatePhone(sVal) { // our phone regular expression // This expression is a very simplex expression that allows null values or 3 digits, dash, //3 digits, dash, 4 digits. It validates a basic US phone number. Written by Jason N. Gaylord.(http://www.regexlib.com) // Matches: [555-555-1212], [123-456-7890] var regex=/^(\d{3}-\d{3}-\d{4})*$/; // do the comparison, if we have a match write thank you or else the email is invalid if (regex.test(sVal)) { return "Thank You"; } else { return "Invalid Phone"; } } function validateZip(sVal) { // our email regular expression //Javascript matches US zipcodes not allowing all zeros in first 5 or +4 (http://www.regexlib.com) // Matches: [12345], [12345-6789], [123456789] var regex=/(^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$)/; // do the comparison, if we have a match write thank you or else the email is invalid if (regex.test(sVal)) { return "Thank You"; } else { return "Invalid ZipCode"; } } function validatePassword(sVal) { //Description: The password's first character must be a letter, it must contain at least 4 characters //and no more than 15 characters and no characters other than letters, numbers and the underscore may be used //Matches: [abcd], [aBc45DSD_sdf], [password] (http://www.regexlib.com) var regex=/^[a-zA-Z]\w{3,14}$/; // do the comparison, if we have a match write thank you or else the email is invalid if (regex.test(sVal)) { return "Thank You"; } else { return "Invalid Password"; } } function validateName(sVal) { //This is the simplest RegEx for validating someone's name. The name can contain only alphabets(in either case) & //should be of minimum length 4 & maximum length 32. Only white spaces are allowed apart from alphabets. //Matches: [some body], [hey there], [hello] (http://www.regexlib.com) var regex=/^([a-zA-z\s]{4,32})$/; // do the comparison, if we have a match write thank you or else the email is invalid if (regex.test(sVal)) { return "Thank You"; } else { return "Invalid Name"; } } function validateNumeric(sVal) { //Input for Numeric values. Handles negatives, and comma formatted values. Also handles a single decimal point //Matches: [5,000], [-5,000], [100.044] (http://www.regexlib.com) var regex=/^(\d|-)?(\d|,)*\.?\d*$/; // do the comparison, if we have a match write thank you or else the email is invalid if (regex.test(sVal)) { return "Thank You"; } else { return "Invalid Number"; } }
codice://Created By: Chris Campbell //www.particletree.com var gErrors = 0; //number of errors is set to none to begin with function validate() { var tables; //variable which will become an array holding all elements with the td tagname // store all <td> elements in the tables array tables = document.getElementsByTagName('td') //loop through all the <td> elements for (i=0; i<tables.length; i++) { // if the class name of that td element is rules check to see if there are error warnings if (tables[i].className == "rules") { //if there is a thank you or its blank then it passes if (tables[i].innerHTML == 'Thank You' || tables[i].innerHTML == '' ) { tables[i].style.color = '#000000';//the color is changed to blank or stays black } else { gErrors = gErrors + 1; //the error count increases by 1 tables[i].style.color = '#ff0000';//error messages are changed to red } } } if (gErrors > 0){ //if there are any errors give a message alert ("Please make sure all fields are properly completed. Errors are marked in red!"); gErrors = 0;// reset errors to 0 return false; } else { alert("The Form Is Valid!"); return false;//set this to true in practice to allow the form to submit } }

Rispondi quotando