2012-04-05 8 views
0

Wie validiere ich TT/MM/JJJJ, numerischer Kreditbetrag, zuerst alphabetisch, Nachname zusammen. Ich habe Probleme mit diesem Forum. Danke für die schnelle Antwort!Wie kann ich mehrere verschiedene Formularfelder validieren, ich habe gesucht und nach einer Woche gesucht

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<script type="text/javascript"> 
<!--// 
function validate(form){ 
    var message = 'Please fill in the following fields:\n\n\t'; 
    for(var i=0; i<form.elements.length; i++){ 
     if(form.elements[i].value.length == 0){ 
      message+= form.elements[i].name.toUpperCase()+'\n\t'; 
     } 
    } 
    message+= '\nOK submit incomplete form'; 
    message+= '\nCANCEL return to the form'; 
    message = confirm(message); 
    if(!message){ return false }; 
    else{ return true }; 
} 
//--> 
</script> 
</head> 
<body> 
    <form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)"> 
     First Name: <input type="text" name="firstname" maxlength="15"><br> 
     Last Name: <input type="text" name="lastname" maxlength="15"><br> 
     Birth Date: <input type="text" name="birthdate" maxlength="8"><br> 
     Loan Amount: <input type="text" name="loanamount" maxlength="6" ><br> 
     Years: <input type="text" name="years" maxlength="2"><br> 
     <br> 
     <input type="reset" value="clear"> 
     <input type="submit" value="submit"> 
    </form>                 
</body> 
</html> 
+1

Zeigen Sie uns Ihre HTML, bitte. – jfriend00

+0

Okay, ich habe = oben. Vielen Dank für Ihre schnelle Antwort! Diane – user1314280

+0

** ProTip: ** Das letzte Bit, das da sein könnte 'return confirm (Nachricht);' – rlemon

Antwort

0

Sie können eine Funktion wie diese verwenden. Sie richtet für jeden Feldtyp einen regulären Ausdruck ein und erstellt dann eine Tabelle, die angibt, welcher reguläre Ausdruck für welches Formularelement verwendet werden soll. Es verwendet die genannten Formularelemente, um auf die einzelnen Werte zuzugreifen.

function validate(form) { 
    var nameRE = /^[A-Za-z \.]+$/; 
    var dateRE = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/; 
    var amountRE = /^\$?[\d\.,]+$/; 
    var yearsRE = /^\d+$/; 

    var formItems = [ 
     {name: "firstname", re: nameRE, tag: "First Name"}, 
     {name: "lastname", re: nameRE, tag: "Last Name"}, 
     {name: "birthdate", re: dateRE, tag: "Birth Date", isDate: true}, 
     {name: "loanamount", re: amountRE, tag: "Loan Amount", min: 50000, max: 750000}, 
     {name: "years", re: yearsRE, tag: "Years", min: 5, max: 30} 
    ]; 

    var item, val, num, month, day, year, valid, matches, incomplete = false; 
    var msg = 'Please fill in the following fields:\n\n\t'; 
    for (var i = 0; i < formItems.length; i++) { 
     item = formItems[i]; 
     // strip leading or trailing whitespace 
     var val = form[item.name].value.replace(/^\s+|\s+$/g, ""); 
     form[item.name].value = val; 
     // see if it matches the regex 
     valid = item.re.test(val); 
     if (valid && item.isDate) { 
      matches = val.match(item.re); 
      month = parseInt(matches[1], 10); 
      day = parseInt(matches[2], 10); 
      year = parseInt(matches[3], 10); 
      if (month <= 0 || month > 12 || 
       day <= 0 || day >= 31 || 
       year < 1900 || year > 2020) { 
       valid = false; 
      } 
     } 
     if (!valid) { 
      incomplete = true; 
      msg += item.tag + '\n\t'; 
     } else { 
      if (item.min && item.max) { 
       // clear out non-numeric chars 
       val = val.replace(/[,\$\s]/g, ""); 
       // convert to a number 
       num = parseInt(val, 10); 
       // compare to min and max 
       if (num < item.min || num > item.max) { 
        incomplete = true; 
        msg += item.tag + " (must be between " + item.min + " and " + item.max + ")\n\t"; 
       } 
      } 
     } 
    } 
    if (incomplete) { 
     msg += '\nOK submit incomplete form'; 
     msg += '\nCANCEL return to the form'; 
     return(confirm(msg)); 
    } 
    return(true); 
} 

Arbeiten Demo hier: http://jsfiddle.net/jfriend00/GChEP/

+0

jfriend du bist fantastisch. Es ist 2 Uhr morgens, aber ich werde es versuchen, vielleicht dauert es eine Weile, lol! – user1314280

0

Eine Art und Weise zu tun wäre, um Klassen zu verwenden, zu wissen, welche Art der Validierung Sie für ein bestimmtes input benötigen. Außerdem können Sie das Attribut title verwenden, um eine menschlichere Darstellung des input zu haben.

Ihre HTML würde dann wie folgt aussehen:

<form name="loanform" action="processform.htm" method="get" onsubmit="return validate(this)"> 
    First Name (text only): <input class="validate-text" title="First Name" type="text" name="firstname" maxlength="15"><br> 
    Last Name (text only): <input class="validate-text" title="Last Name" type="text" name="lastname" maxlength="15"><br> 
    Birth Date (format dd/mm/yyyy): <input class="validate-date" title="Birth Date" type="text" name="birthdate" maxlength="8"><br> 
    Loan Amount (US dollars, numeric only): <input class="validate-number" title="Loan Amount" type="text" name="loanamount" maxlength="6" ><br> 
    Years (numeric only): <input class="validate-number" title="Years" type="text" name="years" maxlength="2"><br> 
    <br> 
    <input type="reset" value="clear"> 
    <input type="submit" value="submit"> 
</form> 

Und Ihre JavaScript-Funktion (reguläre Ausdrücke scheinen der beste Weg zu gehen zu sein):

function validate(f) { 
    var message=new Array(); //will contain the fields that are misfilled 
    var reText=new RegExp("^[a-z \-'\.]+$", "i"); //a RegExp to match names: only letters, "-", "'" and "." allowed 
    var reDate=new RegExp("^[0-9]{2}/[0-9]{2}/[0-9]{4}$"); //a RegExp to match a date in the format dd/mm/yyyy 
    var reNumber=new RegExp("^[0-9]+$"); //a RegExp to match a number 
    for(var e in f.elements) { //loop on every input of the form 
    var test=null; //set or reset the RegExp to use for the current input 
    var input=f.elements[e]; //assign the input to a var (easier to type, not needed) 
    if(!input.className) //if this input doesn't have any class declared 
     continue; //then we skip the rest of the loop to keep going with the next input 
    var classes=input.className.split(" "); //maybe the input has several classes, so we split them in a "classes" array 
    for(var c in classes) { //we loop on every class of the current input 
     switch(classes[c]) { //and we test if the current class of the current input is one of the classes we're interested in 
     case "validate-text": //if it is a text 
      test=reText; //the variable "test" will contain the RegExp we want to use 
      break; 
     case "validate-date": //same for a date 
      test=reDate; 
      break; 
     case "validate-number": //and same for a number 
      test=reNumber; 
      break; 
     default: //if the class is not something we want, nothing to do 
      break; 
     } //end switch 
    } //end classes loop 
    //here test is either null (no "validate-something" class found for the current input), or it contains the RegExp telling us the kind of input we must validate. 
    if(test!=null && !input.value.match(test)) { //if it is not null and if the input's value does not match the RegExp 
     message.push(input.title); //we add the field to the "message" array 
    } 
    } //end input loop 
    if(message.length>0) { //if the arary is not empty, we display a confirm box 
    return confirm("Please correctly fill the following field(s), or click OK to send an incomplete form:\n"+message.join("\n")); 
    } 
    //otherwise, the form is correctly filled, we return true to submit the form 
    return true; 
} 
Verwandte Themen