日期:2014-05-16  浏览次数:20362 次

基于prototype.js验证框架(validation.js)做表单校验
有一个validation框架非常优雅地实现表单校验,它基于prototype和script.aculo.us。
从 http://tetlaw.id.au/view/javascript/really-easy-field-validation 下载,有一个简单而详细的例子说明它的用法 。

I. 首先在页面头部引入js库
<script type='text/javascript' src='prototype.js'></script>
<script type='text/javascript' src='validation.js'></script>
<script type='text/javascript' src='effects.js'></script>


II. 加入一段css代码
<style>
input.disabled {
    border: 1px solid #F2F2F2;
    background-color: #F2F2F2;
}
input.required, textarea.required {
    border: 1px solid #00A8E6;
}
input.validation-failed, textarea.validation-failed {
    border: 1px solid #FF3300;
    color : #FF3300;
}
input.validation-passed, textarea.validation-passed {
    border: 1px solid #00CC00;
    color : #000;
}

.validation-advice {
    margin: 5px 0;
    padding: 5px;
    background-color: #FF3300;
    color : #FFF;
    font-weight: bold;
}
</style>



III. HTML代码
<form id="test" action="#" >
   <table border="1px">
   <tr>
      <td class = "label">Username</td>
      <td><input type="text" name="username" id = "username" class="required"></td>
   </tr>
   <tr>
      <td class = "label">Telephone Number</td>
      <td><input type="text" name="telephoneNumber" class="required validate-alphanum" id = "telephoneNumber"></td>
   </tr>
   <tr>
      <td colspan = "2" align = "center">
      <button class = "submit" id = "search">Search</button>
      </td>
   </tr>
   <table>
</form>
<script>
   var valid = new Validation('test', {immediate : true});
</script>



当运行该页面,如果username不输入任何文字或者telephoNumber输入非数字和字母时,点击search按钮时,将看到错误信息提示。 class="required validate-alphanum" 是validation内建的校验规则名称。当执行new Validation('test', {immediate : true}),Field失去焦点或者执行表单提交动作时,该表单下的所有内建类校验名的校验规则将被触发。