`
jiahh
  • 浏览: 38585 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

jquery验证表单

 
阅读更多
前天看了不错的jquery验证框架这个帖子,自己下在下来看看,感觉还不错。就自己动手试一试。希望大家多多拍砖。
自己汉化了一下,官方只有英文的。

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

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\');  


.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\');
}


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

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> 

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



(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");  
                            }  
                        }  
                    }, 

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

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

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

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的包,自己添加。




分享到:
评论

相关推荐

    jquery表单验证插件

    ##### 4.3 实例:使用ajaxSubmit提交表单 ```javascript $('#myFormId').submit(function(){ $(this).ajaxSubmit(); return false; // 阻止默认提交行为 }); ``` ##### 4.4 实例:序列化表单 ```javascript var ...

    JQuery表单提交和后台交互源码20130509

    仅使用jQuery提交表单和后台交互,不使用基于jQuery的表单插件 方式1、取到页面控件的值后拼接放在data中,传递到后台 方式2、页面序列化后放在data中,传递到后台 注:此种方式需设置页面控件的name属性

    JQuery 提交表单(附详细图解)

    本文将详细讲解如何使用jQuery提交表单,以及如何利用jQuery的AJAX功能来实现无刷新的数据提交。 ### 传统表单提交方式 在没有jQuery的情况下,我们通常会在HTML中创建一个表单,然后通过JavaScript或者JSP/...

    jQuery验证表单插件

    jQuery验证表单插件是一种高效且易于使用的工具,它极大地简化了前端开发人员对用户输入数据的验证过程。在Web应用程序中,表单验证是必不可少的一环,它确保用户提交的信息符合预设的规则,例如非空、邮箱格式、...

    Java Web Jquery表单验证

    编写基于Jquery的表单验证插件 Java Web Jquery表单验证 jQuery是一个流行的JavaScript库,可用于在网页上进行各种操作,包括表单验证。 1、将基于Jquery的表单验证的调查问卷分为四个部分:FrontPage.html、write....

    Ajax使用jQuery提交表单 文件

    在这个“Ajax使用jQuery提交表单 文件”中,我们将探讨如何利用jQuery实现Ajax提交表单,从而实现异步数据传输,提高用户体验。 首先,我们需要理解jQuery中的Ajax函数`$.ajax()`。这是一个核心函数,可以进行各种...

    itcast_tools 验证码加jquery验证表单

    本项目“itcast_tools 验证码加jquery验证表单”专注于提供一个高效且可靠的验证机制,确保用户数据的准确性和安全性。在这个项目中,主要涉及的技术包括Java、IDEA开发环境、验证码生成以及jQuery前端验证。 首先...

    Jquery超强验证表单

    同时,确保在所有验证成功后再提交表单,以防止部分数据未验证就提交。 **10. 源码分析** 通过阅读和理解“jQuery超强验证表单”中的源码,我们可以学习到如何组织和实现一个完整的表单验证系统,包括规则定义、...

    Jquery提交表单 Form.js官方插件介绍

    Jquery提交表单 Form

    自带丰富示例的jQuery验证表单插件

    9. **与其他jQuery插件的兼容性**:由于基于jQuery,这个验证插件能很好地与其它jQuery UI组件或表单增强插件(如Bootstrap Form Validation)协同工作。 在实际应用中,使用jQuery Validate插件通常包括以下步骤:...

    jQuery用户注册表单验证代码

    当用户尝试提交表单时,这个函数会被触发。 接着,我们需要逐个验证表单字段。例如,检查用户名是否为空,可以使用`.val()`获取输入值,然后用`.trim()`去除两侧空格,并通过条件语句判断是否为空。密码强度通常...

    jQuery验证表单属性是否为空

    针对"jQuery验证表单属性是否为空"的主题,我们需要关注以下几个方面: 1. **选择器**:jQuery的选择器用于定位DOM中的特定元素。例如,`$("#myInput")`将选择ID为"myInput"的输入元素。我们可以根据表单字段的ID、...

    jquery表单验证实例,对数字,字数,必填项等校验

    `jQuery Validate`是基于`jQuery`的一个插件,专门用于实现客户端的表单验证,它可以高效且易于地实现对数字、字数、必填项等各种类型的验证。 在"jquery表单验证实例,对数字,字数,必填项等校验"这个项目中,...

    jquery带提示验证表单.zip

    6. **成功反馈**:验证通过后,可以选择性地清除错误信息,并决定是否继续提交表单。如果所有验证都通过,可以使用`.preventDefault()`阻止表单的默认提交行为,然后使用Ajax异步提交,或者直接让表单正常提交。 四...

    JQuery实现表单验证

    对于表单验证,JQuery可以帮助我们快速响应用户的输入,实时检查数据的有效性,无需等待表单提交。 表单验证通常包括以下几种类型:非空验证、长度验证、格式验证(如邮箱、电话号码)、唯一性验证等。在"JQuery...

    jquery表单验证实例网站会员注册表单验证提交form表单代码

    3. **编写jQuery验证代码**: 在`$(document).ready()`函数内,对每个字段编写验证规则。例如,检查密码是否与确认密码匹配,邮箱格式是否正确。 ```javascript $(document).ready(function() { $("#register-...

    jQuery完整注册表单提交验证

    如果所有验证都通过,再提交表单到服务器;否则,显示相应的错误信息。 在实际项目中,还可以考虑使用现有的验证库,如`jQuery Validate Plugin`,它提供了丰富的验证规则和自定义选项,可以简化上述过程。同时,...

    Jquery表单验证特效示例

    9. **AJAX提交**:在验证成功后,可以利用jQuery的AJAX功能无刷新提交表单,进一步提升用户体验。 10. **跨域提交与安全**:在实际应用中,还需要考虑跨域提交的安全问题,比如使用JSONP或CORS策略。 综上所述,...

    jquery validate 表单验证

    5. **触发验证**:当用户提交表单时,可以调用`valid()`方法触发验证。如果表单有效,将执行submit处理程序;否则,阻止表单提交。 6. **自定义验证**:通过扩展验证方法,你可以创建自己的验证规则,以适应特定...

Global site tag (gtag.js) - Google Analytics