数字,日期和值的JSP表单验证

时间:2011-11-08 05:29:28

标签: java javascript eclipse jsp

你好我有一个包含表格的JSP页面,我想验证表格数据,如出生日期格式和价值,品种id - 只有数字的动物园ID和存在的动物名称

这是我的JSP页面:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ page import="java.util.ArrayList" %>
<%@page import="content.*"%>
<%@ page language="java" 
         contentType="text/html; charset=windows-1256"
         pageEncoding="windows-1256" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>



<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>Append Animal</title>
<link rel="stylesheet"
      href="./css/styles.css"
      type="text/css"/>
</head>
<body>
<table class="title">
  <tr><th>Zoo keeper</th></tr>
</table>


<h1>Append Animal</h1>

<form name="insert" action="Relay" >
<fieldset>
Animal new name: <input type= "text" name = "aname"><br>
Animal new DOB: <input type= "text" name = "dob"><br>


Animal new gender: 
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
Animal status: 
<select name="source" id="source">
<option value="born">Born</option>
<option value="bought">Bought</option>
</select>
<br>
Animal old zoo: <input type= "text" name = "zooid" > only if bought<br>
Animal new Breed: <input type= "text" name = "breedid" ><br>
Animal new remarks: <textarea name = "remark" rows="4" cols="20">

</textarea> <br /> <br/>


<input type="submit" value="submit">

<input type="hidden" name="command" value="AppendAnimalServlet" > 

</fieldset>
</form>
</body></html>

我在JSP页面中添加了这个脚本:

<script>
function validateForm()
{
    if(document.insert.aname.value ==="")
    {
      alert("Animal should have a name");
      document.insert.aname.focus();
      return false;
    }
    if(document.insert.zooid.value !=="")
    {
        if (! (/^\d*(?:\.\d{0,2})?$/.test(document.insert.zooid.value))) { 
            alert("Please enter a valid Zoo id"); 
            document.insert.zooid.focus(); 
            return false; 
        } 

      } 
    if(document.insert.breedid.value !=="")
    {
        if (! (/^\d*(?:\.\d{0,2})?$/.test(document.insert.breedid.value))) { 
            alert("Please enter a valid Breed id"); 
            document.insert.breedid.focus(); 
            return false; 
        } 

      } 
    if(document.insert.dob.value ==="")
    {
      alert("Animal should have a date of birth");
      document.insert.aname.focus();
      return false;
    }

}
</script>

但我不认为我这样做对任何有关如何处理此事的建议都没有?

请注意,表单值将被转换为Relay servlet以处理插入过程

<form name="insert" action="Relay" onsubmit="return validateForm();">

2 个答案:

答案 0 :(得分:2)

如果不是作业,请节省一些时间并使用JQuery Validator

 
rules: {    
    dob: {
       required: true,
       date: true },    
    firstname: "required",
    breedid: "required"
}

答案 1 :(得分:0)

验证库可以使用一些通用代码构建,如下所示(只是一个简单的例子,可以大大扩展):

function validate(form) {
  var fnMap = {

    'validate-dateISO8601': {
      checkFn: isValidISO8601,
      checkMsg: 'Date must be in format yyyy-mm-dd'
    },

    'validate-dateValid': {
      checkFn: isValidDate,
      checkMsg: 'Date must be a valid date'
    }
  };

  var reClass = /(^|\s*)validate-[^\s]*/g;
  var control, controls = form.elements;
  var check, checks;
  var fn, value;

  for (var i=0, iLen=controls.length; i<iLen; i++) {
    control = controls[i];

    // Need a function here to handle more control types
    value = control.value;
    checks = control.className.match(reClass);

    // If there are any validate- classes
    if (checks) {

      // For each validate class
      for (var j=0, jLen=checks.length; j<jLen; j++) {
        check = checks[j].replace(/\s/g,'');

        // See if there is a related function
        if (fnMap.hasOwnProperty(check)) {
          check = fnMap[check];

          // If there is, run it
          // If it fails, show the message
          // This part could be collected in an array and all the
          // error messages desplayed at once or in suitable message
          // elements in the document. But alert is cheap :-)
          if (!check.checkFn(value)) {
            alert(check.checkMsg);
            control.focus();
            return false;
          }
        }
      }
    }
  }
}

// Just checks the pattern is yyyy/mm/dd
function isValidISO8601(s) {
    s.replace(/^\s+|\s+$/g, '');
    return /\d{4}[-\/]\d{2}[-\/]\d{2}/.test(s);
} 

// Checks that s is a valid date
function isValidDate(s) {
    var bits = s.split(/[-\/]/g);
    var d = new Date(bits[0], bits[1] - 1, bits[2]);
    return d.getFullYear() == bits[0] && d.getDate() == bits[2];
}

</script>

还有一些HTML

<form onsubmit="return validate(this);">
  <input type="text" name="foo" class="validate-dateISO8601 validate-dateValid" value="2011-02-28">
  <input type="submit">
</form>