jQuery Validation Engine 表單驗證

中文漢化版,官方只有英文的。同時根據中國國情修改了部分驗證規則。

這個插件支持大部分的瀏覽器,但因爲有使用到了css3的陰影和圓角樣式,因此在IE瀏覽器下沒法看到圓角和陰影效果(萬惡的IE)。 javascript

官方下載地址:http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/ php

普通驗證的例子:http://www.position-relative.net/creation/formValidator/ css

ajax驗證的例子:http://www.position-relative.net/creation/formValidator/demoSubmit.html html

一:簡單說明下使用教程:

引入jquery和插件js、css

<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" /> 
<script src="js/jquery.js" type="text/javascript"></script> 
<script src="js/jquery.validationEngine-en.js" type="text/javascript"></script> 
<script src="js/jquery.validationEngine.js" type="text/javascript"></script>
 


jquery.validationEngine-en.js是語言文件,全部的提示都在這個文件找的到,能夠很方便的轉成其餘語言,同時你也能夠在這個文件內定製屬於本身的驗證規則。 java

初始化插件

$(document).ready(function() { 
$("#formID").validationEngine() 
})
 


驗證規則是寫在表單元素的class屬性內。好比下面: jquery

<input value="" class="validate[required,custom[noSpecialCaracters],length[0,20],ajax[ajaxUser]]" type="text" name="user" id="user" />
 


驗證規則很是多樣,基本上包含了全部的數據類型的驗證。
全部的驗證規則寫在validate[]內,有多種驗證,用逗號隔開,這裏簡要說明下經常使用的驗證規則。 css3


required:值不能夠爲空
length[0,100] :文字容許長度
confirm[fieldID] :匹配其餘的表單元素的值,fieldID就是其餘表單元素的id,這個主要用於再次確認密碼
telephone :數據格式要求符合電話格式
email : 數據格式要求符合email 格式
onlyNumber :只容許輸入數字
noSpecialCaracters :不容許出現特殊字符
onlyLetter : 只能是字母
date :必須符合日期格式YYYY-MM-DD


你還能夠在點擊提交按鈕後才觸發驗證。

$("#formID").validationEngine({ 
inlineValidation: false, 
success : false, 
failure : function() { callFailFunction() } 
})
 


默認的是在鼠標失去焦點後纔開始驗證,也就是綁定的是blur事件,那如何改變呢?看下面的配置。

$("#formID").validationEngine({ 
validationEventTriggers:"keyup blur", //will validate on keyup and blur 
success : false, 
failure : function() { callFailFunction() } 
})
 


validationEventTriggers屬性就是修改綁定事件,上面是增長了個keyup,也就是鍵盤按鍵起來就觸發驗證。 web

修改提示層的位置

$("#formID").validationEngine({ 
promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight 
success : false, 
failure : function() { 
})
 


promptPosition就是控制位置,有5種模式:topLeft, topRight, bottomLeft, centerRight, bottomRight ajax

ajax驗證模式

$("#formID").validationEngine({ 
ajaxSubmit: true, 
ajaxSubmitFile: "ajaxSubmit.php", 
ajaxSubmitMessage: "Thank you, we received your inscription!", 
ajaxSubmitExtraData: "securityCode=38709238423&name=john", 
success : false, 
failure : function() {} 
})
 


這幾個參數很好理解。 express


ajaxSubmit: true, 提交表單使用ajax提交
ajaxSubmitFile: 「ajaxSubmit.php」, 後臺腳本
ajaxSubmitMessage 成功後顯示的信息
ajaxSubmitExtraData 參數


這裏須要對後臺腳本返回的數據進行下說明:
返回的數據格式是json。
出現一個錯誤,產生一個數組,以下:

$arrayError[0][0] = "#email"; // FIELDID 
$arrayError[0][1] = "Your email do not match.. whatever it need to match"; // TEXT ERROR 
$arrayError[0][2] = "error"; // BOX COLOR
 


二:修改過的地方

解決ie6下select遮擋div的辦法
jquery.validationEngine.js要修改的地方:

Xml代碼

calculatedPosition.callerTopPosition += "px"; 
calculatedPosition.callerleftPosition += "px"; 
calculatedPosition.marginTopSize += "px"; 
//add matychen 
if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) { 
$(divFormError).append('<iframe class="iframe" frameborder="0" scr="javascript:false;"></iframe>'); 
} 
// add matychen 
$(divFormError).css({ 
"top": calculatedPosition.callerTopPosition, 
"left": calculatedPosition.callerleftPosition, 
"marginTop": calculatedPosition.marginTopSize, 
"opacity": 0 
});
 



validationEngine.jquery.css裏面加入如下代碼:

Java代碼

.iframe { 
position: absolute; 
width: expression(this.parentNode.offsetWidth+\'px\'); 
height: expression(this.parentNode.offsetHeight-32+\'px\'); 
z-index: -1; 
top: expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\'); 
left: expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\'); 
}
 


formvalidator.html以下:

Java代碼

 

<!DOCTYPE HTML PUBLIC "-//IETF//DTD LEVEL1//EN"> 
<html> 
<head> 
<title>formvalidator.html</title> 

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="this is my page"> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
<link rel="stylesheet" href="formValidator/css/validationEngine.jquery.css" type="text/css" /> 
<link rel="stylesheet" href="formValidator/css/template.css" type="text/css" /> 
<script src="formValidator/jquery.js" type="text/javascript"></script> 
<script src="formValidator/js/jquery.validationEngine-cn.js" type="text/javascript"></script> 
<script src="formValidator/js/jquery.validationEngine.js" type="text/javascript"></script> 


<script> 
$(document).ready(function() { 
$("#formID").validationEngine({ 
validationEventTriggers:"blur", //觸發的事件 validationEventTriggers:"keyup blur", 
inlineValidation: true,//是否即時驗證,false爲提交表單時驗證,默認true 
success : false,//爲true時即便有不符合的也提交表單,false表示只有所有經過驗證了才能提交表單,默認false 
promptPosition: "topRight",//提示所在的位置,topLeft, topRight, bottomLeft, centerRight, bottomRight 
//failure : function() { alert("驗證失敗,請檢查。"); }//驗證失敗時調用的函數 
//success : function() { callSuccessFunction() },//驗證經過時調用的函數 
}); 
}); 
</script> 
</head> 

<body> 
<form id="formID" class="formular" method="post" action=""> 
<fieldset> 
<legend>User informations</legend> 
<label> 
<span>Desired username (ajax validation, only karnius is available) : </span> 
<input value="" class="validate[required,custom[noSpecialCaracters],length[0,20],ajax[ajaxUser]]" type="text" name="user" id="user" />//ajax驗證用戶名的地方 
</label> 
<label> 
<span>First name (optional)</span> 
<input value="karnius" class="validate[optional,custom[onlyLetter],length[0,100]] text-input" type="text" name="firstname" id="firstname" /> 
</label> 
<label> 
<span>Last name : </span> 
<input value="karnius" class="validate[required,custom[onlyLetter],length[0,100]] text-input" type="text" id="data[Use6][preferedColor]" name="lastname" /> 
</label> 
<div> 
<span>Radio Groupe : <br /></span> 
<span>radio 1: </span> 
<input class="validate[required] radio" type="radio" name="data[User][preferedColor]" id="radio1" value="5"> 
<span>radio 2: </span> 
<input class="validate[required] radio" type="radio" name="data[User][preferedColor]" id="radio2" value="3"/> 
<span>radio 3: </span> 
<input class="validate[required] radio" type="radio" name="data[User][preferedColor]" id="radio3" value="9"/> 
</div> 
<div> 
<span>Minimum 2 checkbox : <br /></span> 

<input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="data[User3][preferedColor]" value="5"> 
<input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="data[User3][preferedColor]" value="5"> 

<input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="maxcheck2" value="3"/> 

<input class="validate[minCheckbox[2],maxCheckbox[3]] checkbox" type="checkbox" name="data[User3][preferedColor]" id="maxcheck3" value="9"/> 
</div> 
<label> 
<span>Date : (format YYYY-MM-DD)</span> 
<input value="1111-11-11" class="validate[required,custom[date]] text-input" type="text" name="date" id="date" /> 
</label> 
<label> 
<span>Favorite sport 1:</span> 
<select name="sport" id="sport" class="validate[required]" id="sport" > 
<option value="">Choose a sport</option> 
<option value="option1">Tennis</option> 
<option value="option2">Football</option> 
<option value="option3">Golf</option> 
</select> 
</label> 
<label> 
<span>Favorite sport 2:</span> 
<select name="sport2" id="sport2" multiple class="validate[required]" id="sport2" > 
<option value="">Choose a sport</option> 
<option value="option1">Tennis</option> 
<option value="option2">Football</option> 
<option value="option3">Golf</option> 
</select> 
</label> 
<label> 
<span>Age : </span> 
<input value="22" class="validate[required,custom[onlyNumber],length[0,3]] text-input" type="text" name="age" id="age" /> 
</label> 

<label> 
<span>Telephone : </span> 
<input value="1111111" class="validate[required,custom[telephone]] text-input" type="text" name="telephone" id="telephone" /> 
</label> 
<label> 
<span>mobilephone : </span> 
<input value="111111" class="validate[required,custom[mobilephone]] text-input" type="text" name="telphone" id="telphone" /> 
</label> 
<label> 
<span>chinese : </span> 
<input value="asdf" class="validate[required,custom[chinese]] text-input" type="text" name="chinese" id="chinese" /> 
</label> 
<label> 
<span>url : </span> 
<input value="url" class="validate[required,custom[url]] text-input" type="text" name="url" id="url" /> 
</label> 
<label> 
<span>zipcode : </span> 
<input value="zipcode" class="validate[required,custom[zipcode]] text-input" type="text" name="zipcode" id="zipcode" /> 
</label> 
<label> 
<span>ip : </span> 
<input value="ip" class="validate[required,custom[ip]] text-input" type="text" name="ip" id="ip" /> 
</label> 
<label> 
<span>qq : </span> 
<input value="01234" class="validate[required,custom[qq]] text-input" type="text" name="qq" id="qq" /> 
</label> 
</fieldset> 
<fieldset> 
<legend>Password</legend> 
<label> 
<span>Password : </span> 
<input value="karnius" class="validate[required,length[6,11]] text-input" type="password" name="password" id="password" /> 
</label> 
<label> 
<span>Confirm password : </span> 
<input value="karnius" class="validate[required,confirm[password]] text-input" type="password" name="password2" id="password2" /> 
</label> 
</fieldset> 
<fieldset> 
<legend>Email</legend> 
<label> 
<span>Email address : </span> 
<input value="ced@hotmail.com" class="validate[required,custom[email]] text-input" type="text" name="email" id="email" /> 
</label> 
<label> 
<span>Confirm email address : </span> 
<input value="ced@hotmail.com" class="validate[required,confirm[email]] text-input" type="text" name="email2" id="email2" /> 
</label> 
</fieldset> 
<fieldset> 
<legend>Comments</legend> 
<label> 
<span>Comments : </span> 
<textarea value="ced@hotmail.com" class="validate[required,length[6,300]] text-input" name="comments" id="comments" /> </textarea> 
</label> 

</fieldset> 
<fieldset> 
<legend>Conditions</legend> 
<div class="infos">Checking this box indicates that you accept terms of use. If you do not accept these terms, do not use this website : </div> 
<label> 
<span class="checkbox">I accept terms of use : </span> 
<input class="validate[required] checkbox" type="checkbox" id="agree" name="agree"/> 
</label> 
</fieldset> 
<input class="submit" type="submit" value="Validate & Send the form!"/> 
<hr/> 
</form> 
</body> 
</html>
jquery.validationEngine-cn.js以下:

Java代碼

(function($) { 
$.fn.validationEngineLanguage = function() {}; 
$.validationEngineLanguage = { 
newLang: function() { 
$.validationEngineLanguage.allRules = {"required":{ // Add your regex rules here, you can take telephone as an example 
"regex":"none", 
"alertText":"* 非空選項.", 
"alertTextCheckboxMultiple":"* 請選擇一個單選框.", 
"alertTextCheckboxe":"* 請選擇一個複選框."}, 
"length":{ 
"regex":"none", 
"alertText":"* 長度必須在 ", 
"alertText2":" 至 ", 
"alertText3": " 之間."}, 
"maxCheckbox":{ 
"regex":"none", 
"alertText":"* 最多選擇 ",//官方文檔這裏有問題 
"alertText2":" 項."}, 
"minCheckbox":{ 
"regex":"none", 
"alertText":"* 至少選擇 ", 
"alertText2":" 項."}, 
"confirm":{ 
"regex":"none", 
"alertText":"* 兩次輸入不一致,請從新輸入."}, 
"telephone":{ 
"regex":"/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/", 
"alertText":"* 請輸入有效的電話號碼,如:010-29292929."}, 
"mobilephone":{ 
"regex":"/(^0?[1][358][0-9]{9}$)/", 
"alertText":"* 請輸入有效的手機號碼."}, 
"email":{ 
"regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/", 
"alertText":"* 請輸入有效的郵件地址."}, 
"date":{ 
"regex":"/^(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)$/", 
"alertText":"* 請輸入有效的日期,如:2008-08-08."}, 
"ip":{ 
"regex":"/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/", 
"alertText":"* 請輸入有效的IP."}, 
"chinese":{ 
"regex":"/^[\u4e00-\u9fa5]+$/", 
"alertText":"* 請輸入中文."}, 
"url":{ 
"regex":"/^[a-zA-z]:\\/\\/[^s]$/",//這些驗證請本身增強 
"alertText":"* 請輸入有效的網址."}, 
"zipcode":{ 
"regex":"/^[1-9]\d{5}$/", 
"alertText":"* 請輸入有效的郵政編碼."}, 
"qq":{ 
"regex":"/^[1-9]\d{4,9}$/", 
"alertText":"* 請輸入有效的QQ號碼."}, 
"onlyNumber":{ 
"regex":"/^[0-9]+$/", 
"alertText":"* 請輸入數字."}, 
"onlyLetter":{ 
"regex":"/^[a-zA-Z]+$/", 
"alertText":"* 請輸入英文字母."}, 
"noSpecialCaracters":{ 
"regex":"/^[0-9a-zA-Z]+$/", 
"alertText":"* 請輸入英文字母和數字."}, 
"ajaxUser":{ 
"file":"validate.action",//ajax驗證用戶名,會post以下參數:validateError ajaxUser;validateId user;validateValue cccc 
"alertTextOk":"* 賬號能夠使用.", 
"alertTextLoad":"* 檢查中, 請稍後...", 
"alertText":"* 賬號不能使用."}, 
"ajaxName":{ 
"file":"validateUser.php", 
"alertText":"* This name is already taken", 
"alertTextOk":"* This name is available", 
"alertTextLoad":"* Loading, please wait"} 
} 
} 
} 
})(jQuery); 

$(document).ready(function() { 
$.validationEngineLanguage.newLang() 
});
 

 
部分jquery.validationEngine.js
Java代碼

/* AJAX VALIDATION HAS ITS OWN UPDATE AND BUILD UNLIKE OTHER RULES */ 
if(!ajaxisError){ 
$.ajax({ 
type: "POST", 
url: postfile, 
async: true, 
data: "validateValue="+fieldValue+"&validateId="+fieldId+"&validateError="+customAjaxRule,//+extraData,//本身把其中的+extraData去掉了,否則後面的ajax驗證有問題。 
beforeSend: function(){ // BUILD A LOADING PROMPT IF LOAD TEXT EXIST 
if($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad){ 

if(!$("div."+fieldId+"formError")[0]){ 
return $.validationEngine.buildPrompt(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load"); 
}else{ 
$.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load"); 
} 
} 
},
 

struts.xml文件:

Java代碼

 

<struts> 
<package name="json" extends="json-default"> 
<!--驗證--> 
<action name="validate" class="com.bw30.zjvote.action.ValidateAction" 
method="vali"> 
<result type="json"> 
<param name="excludeProperties">msg</param>//jsonplugin-0.32.jar 
</result> 
</action> 

</package> 
</struts>
 


validateAction

Java代碼

public String vali() { 
ActionContext ac = ActionContext.getContext(); 
HttpServletRequest request = (HttpServletRequest) ac 
.get(ServletActionContext.HTTP_REQUEST); 
String validateId = request.getParameter("validateId"); 
logger.info("vali() - String validateId=" + validateId); 

String validateValue = request.getParameter("validateValue"); 
String validateError = request.getParameter("validateError"); 
logger.info("vali() - String validateError=" + validateError); 
//注意下面的順序,感受這是個缺陷之一,不過能夠在jquery.validationEngine.js更改, 
jsonValidateReturn.add(validateId); 
jsonValidateReturn.add(validateError); 
if(validateValue.equals("chen")) 
jsonValidateReturn.add("true"); 
else 
jsonValidateReturn.add("false"); 
return SUCCESS; 
}
 

jquery.validationEngine.js要更改的地方:

Java代碼

success: function(data){ // GET SUCCESS DATA RETURN JSON 
data = eval( "("+data+")"); // GET JSON DATA FROM PHP AND PARSE IT 
ajaxisError = data.jsonValidateReturn[2];//這裏官方文檔寫死了,能夠根據本身需求更改。 
customAjaxRule = data.jsonValidateReturn[1];//這裏官方文檔寫死了,能夠根據本身需求更改。 
ajaxCaller = $("#"+data.jsonValidateReturn[0])[0]; 
fieldId = ajaxCaller; 
ajaxErrorLength = $.validationEngine.ajaxValidArray.length; 
existInarray = false; 

if(ajaxisError == "false"){ // DATA FALSE UPDATE PROMPT WITH ERROR; 

_checkInArray(false) // Check if ajax validation alreay used on this field 

if(!existInarray){ // Add ajax error to stop submit 
$.validationEngine.ajaxValidArray[ajaxErrorLength] = new Array(2); 
$.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId; 
$.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false; 
existInarray = false; 
}

用到了jsonplugin-0.32.jar這個包在附件裏面,其餘struts的包,本身添加。

相關文章
相關標籤/搜索