最近对prototype.js用的比较多,同时发现了一个基于prototype.js的验证框架: validation.js really easy field validation with prototype,下面是我在开发中用到的三个例子.
前提条件:
首先要在html页面中引入几个js
(可选)
加几段css
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; }
应用一:该例子仅使用前台脚本进行验证
需求:
查询条件
当CSO NO、AGREEMENT NO、流水号中任一项有值时,其他项都可为空
2. 当CSO NO、AGREEMENT NO、流水号三项都为空时,TARIFF CODE为必输,其他项选输
CSO Number Agreement Number SequenceNumber Number Tariff Code
window.onload = function(){ // 注册查询按钮事件 Event.observe("search", "click", function(){ var validator = Validation.get("IsEmpty"); if ([$F("csoNumber"), $F("agreementNumber"), $F("sequenceNumber")].all(validator.test)){ ["required"].all(Validation.test.bind($("tariffCode"))); } });
应用二: 该例子通过ajax结合后台来进行验证
需求:
sapid和password必输
且必须从后台数据库找到sapid和password对应的记录, 否则登陆不成功,并给出提示信息
window.onload = function(){ // 自定义验证器并注册到Validation中 var validatorName = "validate-login-info"; Validation.add(validatorName, "", function(){return false;}); // 验证器初始化 var validator = new Validation('frmLogin', {stopOnFirst:true, immediate:true}); // 提交前进行后台验证 Event.observe("frmLogin", "submit", function(ev){ var result = validator.validate(); if (result){ var request = new Ajax.Request( "http://localhost:8080/agreement/CheckLoginInfo", // 提交的URL { method: 'get', asynchronous: false, parameters: Form.serialize("frmLogin"), }); // 验证不通过,显示出错信息, 并中止提交操作! var transport = request.transport; if (transport.responseText != ""){ Validation.get(validatorName).error = transport.responseText; [validatorName].all(Validation.test.bind($("errMsg"))); Event.stop(ev); } } }) }
应用三:
需求:典型注册应用, 密码和确认密码的一致性验证
window.onload = function(){ // 添加password一致性验证 Validation.add("validate-identical", "the value of password and repassword must be identical", function(v){ return !Validation.get('IsEmpty').test(v) && v == $F("password"); }) // 验证器注册 var validator = new Validation('frmRegister', {stopOnFirst:true, immediate:true}); }