如何验证多个不同的表单字段,我已搜索并搜索了一周

时间:2012-04-05 03:26:27

标签: javascript forms

如何验证dd / mm / yyyy,数字贷款金额,字母首字母,姓氏。我在使用这个论坛时遇到了麻烦。感谢您的回复如此之快!

<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>

2 个答案:

答案 0 :(得分:0)

您可以使用这样的功能。它为每种类型的字段设置一个正则表达式,然后创建一个表,说明哪个正则表达式用于哪个表单元素。它使用命名的表单元素来访问各个值。

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);
}

这里的工作演示:http://jsfiddle.net/jfriend00/GChEP/

答案 1 :(得分:0)

要做的一种方法是使用类来了解给定input所需的验证类型。此外,您可以使用title属性对input进行更人性化的表示。

您的HTML将如下所示:

<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>

你的JavaScript函数(正则表达式似乎是最好的方法):

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;
}