validationEngine中文版 — jquery强大的表单验证插件(做了些小修改)

中文汉化版,官方只有英文的。修改了部分验证规则。

这个插件支持大部分的浏览器,但由于有使用到了css3的阴影和圆角样式,所以在IE浏览器下无法看到圆角和阴影效果(万恶的IE)。

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

普通验证的例子:http://www.position-relative.net/creation/formValidator/

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

一:简单说明下使用教程:

引入jquery和插件js、css

  1. <link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css" media="screen" charset="utf-8" /> 
  2. <link type="text/css" rel="Stylesheet" href="css/template.css" />
  3. <link type="text/css" rel="Stylesheet" href="css/css.css" />
  4. <script src="js/jquery.js" type="text/javascript"></script> 
  5. <script src="js/jquery.validationEngine-en.js" type="text/javascript"></script> 
  6. <script src="js/jquery.validationEngine.js" type="text/javascript"></script>

jquery.validationEngine-en.js是语言文件,所有的提示都在这个文件找的到,可以很方便的转成其他语言,同时你也可以在这个文件内定制属于自己的验证规则。

初始化插件

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

验证规则是写在表单元素的class属性内。比如下面:

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

验证规则非常多样,基本上包含了所有的数据类型的验证。
所有的验证规则写在validate[]内,有多种验证,用逗号隔开,这里简要说明下常用的验证规则。

  1. required:值不可以为空
  2. length[0,100] :文字允许长度
  3. minSize:最小字符长度
  4. maxSize:最大字符长度
  5. min:最小值
  6. max:最大值
  7. equals[fieldID] :匹配其他的表单元素的值,fieldID就是其他表单元素的id,这个主要用于再次确认密码
  8. telephone :数据格式要求符合电话格式
  9. email : 数据格式要求符合email 格式
  10. onlyNumber :只允许输入数字
  11. noSpecialCaracters :不允许出现特殊字符
  12. onlyLetter : 只能是字母
  13. date :必须符合日期格式YYYY-MM-DD

你还可以在点击提交按钮后才触发验证。

  1. $("#formID").validationEngine({ 
  2. inlineValidation: false,
  3. successfalse,
  4. failure : function() { callFailFunction()  } 
  5. })

默认的是在鼠标失去焦点后才开始验证,也就是绑定的是blur事件,那如何改变呢?看下面的配置。

  1. $("#formID").validationEngine({ 
  2. validationEventTriggers:"keyup blur"//will validate on keyup and blur  
  3. successfalse,
  4. failure : function() { callFailFunction()  } 
  5. })

validationEventTriggers属性就是修改绑定事件,上面是增加了个keyup,也就是键盘按键起来就触发验证。

修改提示层的位置

  1. $("#formID").validationEngine({ 
  2. promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
  3. successfalse,
  4. failure : function() { 
  5. })

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

错误显示方式

  1. $("#formID").validationEngine({ 
  2. promptPosition: "topRight", // OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft,  centerRight, bottomRight
  3. showTypes:2,//默认是1
  4. successfalse,
  5. failure : function() { 
  6. })

ajax验证模式

  1. $("#formID").validationEngine({ 
  2.  ajaxSubmit: true,
  3.   ajaxSubmitFile: "ajaxSubmit.php",
  4.   ajaxSubmitMessage: "Thank you, we received your inscription!",
  5.  ajaxSubmitExtraData: "securityCode=38709238423&name=john",
  6.  successfalse,
  7.  failure : function() {} 
  8. })

这几个参数很好理解。

  1. ajaxSubmit: true, 提交表单使用ajax提交
  2. ajaxSubmitFile: “ajaxSubmit.php”, 后台脚本
  3. ajaxSubmitMessage 成功后显示的信息
  4. ajaxSubmitExtraData 参数

这里需要对后台脚本返回的数据进行下说明:
返回的数据格式是json。
出现一个错误,产生一个数组,如下:

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

源代码

jquery.validationEngine-en.js 

1 (function($){
2 $.fn.validationEngineLanguage = function(){
3 };
4 $.validationEngineLanguage = {
5 newLang: function(){
6 $.validationEngineLanguage.allRules = {
7 "required": { // Add your regex rules here, you can take telephone as an example
8   "regex": "none",
9 "alertText": "* 非空选项.",
10 "alertTextCheckboxMultiple": "* 请选择一个单选框.",
11 "alertTextCheckboxe": "* 请选择一个复选框."
12 },
13 "length":{
14 "regex":"none",
15 "alertText":"* 长度必须在 ",
16 "alertText2":"",
17 "alertText3": " 之间."},
18
19 "minSize": {
20 "regex": "none",
21 "alertText": "* 最小",
22 "alertText2": " 允许的字符"
23 },
24 "maxSize": {
25 "regex": "none",
26 "alertText": "* 最大 ",
27 "alertText2": " 允许的字符"
28 },
29 "min": {
30 "regex": "none",
31 "alertText": "* 最小的值是 "
32 },
33 "max": {
34 "regex": "none",
35 "alertText": "* 最大的值是 "
36 },
37 "past": {
38 "regex": "none",
39 "alertText": "* Date prior to "
40 },
41 "future": {
42 "regex": "none",
43 "alertText": "* Date past "
44 },
45 "maxCheckbox": {
46 "regex": "none",
47 "alertText": "* 最多选择 ",
48 "alertText2": " 项."
49 },
50 "minCheckbox": {
51 "regex": "none",
52 "alertText": "* 至少选择 ",
53 "alertText2": ""
54 },
55 "telephone":{
56 "regex":"/^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$/",
57 "alertText":"* 请输入有效的电话号码,如:010-29292929."
58 },
59 "mobilephone":{
60 "regex":"/^(13[0-9]|15[^4]|18[6|8|9])\d{8}$/",
61 "alertText":"* 请输入有效的手机号码."
62 },
63 "email":{
64 "regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
65 "alertText":"* 请输入有效的邮件地址."
66 },
67 "chinese":{
68 "regex":"/^[\u4e00-\u9fa5]+$/",
69 "alertText":"* 请输入中文."
70 },
71 "equals": {
72 "regex": "none",
73 "alertText": "* 两次输入不一致,请重新输入."
74 },
75 "phone": {
76 // credit: jquery.h5validate.js / orefalo
77   "regex": /^([\+][0-9]{1,3}[ \.\-])?([\(]{1}[0-9]{2,6}[\)])?([0-9 \.\-\/]{3,20})((x|ext|extension)[ ]?[0-9]{1,4})?$/,
78 "alertText": "* Invalid phone number"
79 },
80 "zipcode":{
81 "regex":"/^[1-9]\d{5}$/",
82 "alertText":"* 请输入有效的邮政编码."
83 },
84 "qq":{
85 "regex":"/^[1-9]\d{4,9}$/",
86 "alertText":"* 请输入有效的QQ号码."
87 },
88
89  // "email": {
90  // // Shamelessly lifted from Scott Gonzalez via the Bassistance Validation plugin http://projects.scottsplayground.com/email_address_validation/
91  // "regex": /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
92  // "alertText": "* Invalid email address"
93  // },
94 "integer": {
95 "regex": /^[\-\+]?\d+$/,
96 "alertText": "* 不是有效的整数"
97 },
98 "number": {
99 // Number, including positive, negative, and floating decimal. credit: orefalo
100 "regex": /^[\-\+]?(([0-9]+)([\.,]([0-9]+))?|([\.,]([0-9]+))?)$/,
101 "alertText": "* 无效的浮点十进制数"
102 },
103 "date": {
104 "regex": /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/,
105 "alertText": "* 请输入有效的日期,如:2008-08-08."
106 },
107 "ip": {
108 "regex": /^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/,
109 "alertText": "* 请输入有效的IP."
110 },
111 "url": {
112 "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
113 "alertText": "* 请输入有效的网址."
114 },
115 "onlyNumber": {
116 "regex": /^[0-9\ ]+$/,
117 "alertText": "* 请输入数字."
118 },
119 "onlyLetter": {
120 "regex": /^[a-zA-Z\ \']+$/,
121 "alertText": "* 请输入英文字母."
122 },
123 "onlyLetterNumber": {
124 "regex": /^[0-9a-zA-Z]+$/,
125 "alertText": "* 请输入英文字母和数字."
126 },
127 // --- CUSTOM RULES -- Those are specific to the demos, they can be removed or changed to your likings
128 "ajaxUser": {
129 "file": "ajaxback.aspx",
130 // you may want to pass extra data on the ajax call
131 "alertTextOk": "* 账号可以使用.",
132 "alertText": "* 账号已被注册.",
133 "alertTextLoad": "* 检查中,请稍候..."
134 },
135 "CheckIDC":
136 {
137 "nname":"CheckIDC",
138 "alertText":"* 身份证号码格式不对."
139 },
140 "validate2fields": {
141 "alertText": "* Please input HELLO"
142 }
143 };
144
145 }
146 };
147 $.validationEngineLanguage.newLang();
148 })(jQuery);

jquery.validationEngine.js

CSS.CSS

View Code
1 /* common css ============================================== */
2 body{margin:20px auto; color:#7d8289; font: 12px/1.5 tahoma, arial, \5b8b\4f53, sans-serif;}
3 :focus{outline:none;}
4 form{margin:0; padding:0;}
5 input,select,textarea{font-size:1em; margin:0; color:#000; font-family:tahoma, arial, simsun, sans-serif;}
6 table{border-collapse:collapse; border-spacing:0;}
7 .rt2{position:relative;top:2px;}
8 .gray{color:#aaa;}
9 h1{color:#000; font-family:"microsoft yahei"; font-weight:normal;}
10 .registerform,h1{
11 padding-left:104px;
12 }
13 .registerform .need{
14 width:10px;
15 color:#b20202;
16 }
17 .registerform td{
18 padding:5px 0;
19 vertical-align:top;
20 text-align:left;
21 }
22 .registerform .inputxt,.registerform textarea{
23 border:1px solid #a5aeb6;
24 width:196px;
25 padding:2px;
26 }
27 .registerform textarea{
28 height:75px;
29 }
30 .registerform label{
31 margin:0 26px 0 10px;
32 }
33 .registerform .tip{
34 line-height:20px;
35 color:#5f6a72;
36 }
37 .registerform select{
38 width:202px;
39 }
40 .registerformalter select{
41 width:124px;
42 }
43
44 /*==========以下部分是必须的===========*/
45 .Validform_checktip{
46 margin-left:8px;
47 line-height:20px;
48 height:20px;
49 overflow:hidden;
50 color:#999;
51 font-size:12px;
52 }
53 .Validform_right{
54 color:#71b83d;
55 padding-left:20px;
56 background:url(../images/right.png) no-repeat left center;
57 }
58 .Validform_wrong{
59 color:red;
60 padding-left:20px;
61 white-space:nowrap;
62 background:url(../images/error.png) no-repeat left center;
63 }
64 .Validform_loading{
65 padding-left:20px;
66 background:url(../images/onLoad.gif) no-repeat left center;
67 }
68 .Validform_error{
69 background-color:#ffe7e7;
70 }
71 #Validform_msg{color:#7d8289; font: 12px/1.5 tahoma, arial, \5b8b\4f53, sans-serif; width:280px; -webkit-box-shadow:2px 2px 3px #aaa; -moz-box-shadow:2px 2px 3px #aaa; background:#fff; position:absolute; top:0px; right:50px; z-index:99999; display:none;filter: progid:DXImageTransform.Microsoft.Shadow(Strength=3, Direction=135, Color='#999999');}
72 #Validform_msg .iframe{position:absolute; left:0px; top:-1px; z-index:-1;}
73 #Validform_msg .Validform_title{line-height:25px; height:25px; text-align:left; font-weight:bold; padding:0 8px; color:#fff; position:relative; background-color:#000;}
74 #Validform_msg a.Validform_close:link,#Validform_msg a.Validform_close:visited{line-height:22px; position:absolute; right:8px; top:0px; color:#fff; text-decoration:none;}
75 #Validform_msg a.Validform_close:hover{color:#cc0;}
76 #Validform_msg .Validform_info{padding:8px;border:1px solid #000; border-top:none; text-align:left;}

demo

View Code
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="validForm.WebForm3" %>
2
3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml">
5 <head runat="server">
6 <title>无标题页</title>
7 <link type="text/css" rel="Stylesheet" href="css1.7/validationEngine.jquery.css" />
8 <link type="text/css" rel="Stylesheet" href="css1.7/template.css" />
9 <link type="text/css" rel="Stylesheet" href="css.css" />
10 <script type="text/javascript" src="JS2.2/jquery-1.6.min.js">
11 </script>
12 <script type="text/javascript" src="js1.7/jquery.validationEngine修改版1.2.js"></script>
13 <script type="text/javascript" src="js2.2/jquery.validationEngine-en.js"></script>
14 <script type="text/javascript">
15 $(document).ready(function() {
16 $("#formID").validationEngine({
17 promptPosition:"centerRight",
18 showTypes:2
19 });
20 //$.validationEngine.loadValidation("#date")
21 //alert($("#formID").validationEngine({returnIsValid:true}))
22 //$.validationEngine.buildPrompt("#date","This is an example","error") // Exterior prompt build example
23 //$.validationEngine.closePrompt(".formError",true) // CLOSE ALL OPEN PROMPTS
24 });
25 function CheckIDC(field, rules, i)
26 {
27 if (CheckIdNumber($("#txtIDC").val()) !="") {
28 return false;
29 // this allows to use i18 for the error msgs
30 // return options.allrules.validate2fields.alertText;
31 }
32 else
33 {
34 return true;
35 }
36 }
37 </script>
38 </head>
39 <body>
40 <form id="formID" runat="server">
41 <table width="100%" style="table-layout: fixed;">
42 <tr>
43 <td class="need" style="width: 10px;">
44 *
45 </td>
46 <td style="width: 70px;">
47 用户名:
48 </td>
49 <td style="width: 205px;">
50 <asp:TextBox ID="txtPassord" runat="server" CssClass="validate[required,length[2,4],ajax[ajaxUser]]"></asp:TextBox>
51 </td>
52 <td>
53 <div class="Validform_checktip">
54 昵称至少6个字符,最多18个字符</div>
55 </td>
56 </tr>
57 <tr>
58 <td class="need">
59 *
60 </td>
61 <td>
62 密码:
63 </td>
64 <td>
65 <input type="password" value="" name="userpassword" class="validate[required,length[2,4]]" />
66 </td>
67 <td>
68 <div class="Validform_checktip">
69 密码范围在6~16位之间,不能使用空格</div>
70 </td>
71 </tr>
72 <tr>
73 <td class="need">
74 *
75 </td>
76 <td>
77 确认密码:
78 </td>
79 <td>
80 <input type="password" value="" name="userpassword2" class="inputxt" />
81 </td>
82 <td>
83 <div class="Validform_checktip">
84 两次输入密码需一致</div>
85 </td>
86 </tr>
87 <tr>
88 <td class="need">
89 </td>
90 <td>
91 Email:
92 </td>
93 <td>
94 <input type="text" value="" name="email" class="inputxt" />
95 </td>
96 <td>
97 <div class="Validform_checktip">
98 请输入您常用的邮箱</div>
99 </td>
100 </tr>
101 <tr>
102 <td class="need">
103 *
104 </td>
105 <td>
106 性别:
107 </td>
108 <td>
109
110 </td>
111 <td>
112 <div class="Validform_checktip">
113 </div>
114 </td>
115 </tr>
116 <tr>
117 <td class="need">
118 *
119 </td>
120 <td>
121 省份:
122 </td>
123 <td>
124 <select name="province" id="province" class="validate[required]">
125 <option value="">--请选择省份--</option>
126 <option value="1">江西省</option>
127 </select>
128 </td>
129 <td>
130 <div class="Validform_checktip">
131 </div>
132 </td>
133 </tr>
134 <tr>
135 <td class="need">
136 *
137 </td>
138 <td>
139 购物网:
140 </td>
141 <td>
142 <input name="shoppingsite2" id="shoppingsite21" type="checkbox" value="1"
143 class="validate[required]" /><label for="shoppingsite21">淘宝网</label>&nbsp;&nbsp;
144 <input name="shoppingsite2" class="rt2" id="shoppingsite22" type="checkbox" value="2" /><label
145 for="shoppingsite22">当当网</label>
146 </td>
147 <td>
148 <div class="Validform_checktip">
149 </div>
150 </td>
151 </tr>
152 <tr>
153 <td class="need">
154 </td>
155 <td>
156 </td>
157 <td colspan="2" style="padding: 10px 0 18px 0;">
158 <asp:Button ID="btnOk" runat="server" onclick="btnOk_Click" Text="提交" />
159 <input type="reset" value="重 置" />
160 </td>
161 </tr>
162 </table>
163 </form>
164 </body>
165 </html>

ajaxback.aspx 验证用户是否已注册

View Code
1 using System;
2 using System.Collections;
3 using System.Configuration;
4 using System.Data;
5 using System.Linq;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13
14 namespace validForm.phpajax
15 {
16 public partial class ajaxback : System.Web.UI.Page
17 {
18 protected void Page_Load(object sender, EventArgs e)
19 {
20 if (!IsPostBack)
21 {
22 //string str = Request.QueryString["fieldValue"].ToString();
23 //string validateId = Request.QueryString["fieldId"].ToString();
24 //if (str != "zrj")
25 //{
26 // Response.Write("true");
27 // Response.End();
28 //}
29 //else
30 //{
31 // Response.Write("false");
32 // Response.End();
33 //}
34 }
35 string str = Request.Form["validateValue"].ToString();
36 string validateId = Request.Form["validateId"].ToString();
37 string validateError = Request.Form["validateError"].ToString();
38 if (str != "zrj")
39 {
40 Response.Write("{'jsonValidateReturn':['" + validateId + "','" + validateError + "','true']}");
41 Response.End();
42 }
43 else
44 {
45 Response.Write("{'jsonValidateReturn':['" + validateId + "','" + validateError + "','false']}");
46 Response.End();
47 }
48 }
49 }
50 }

/*
 * Inline Form Validation Engine 1.7.3, jQuery plugin
 * 
 * Copyright(c) 2010, Cedric Dugas
 * http://www.position-absolute.com
 *	
 * Form validation engine allowing custom regex rules to be added.
 * Thanks to Francois Duquette and Teddy Limousin 
 * and everyone helping me find bugs on the forum
 * Licenced under the MIT Licence
 * zrj 2011-7-5
 */
 (function($) {
	
	$.fn.validationEngine = function(settings) {
		
	if($.validationEngineLanguage){				// IS THERE A LANGUAGE LOCALISATION ?
		allRules = $.validationEngineLanguage.allRules;
	}else{
		$.validationEngine.debug("Validation engine rules are not loaded check your external file");
	}
 	settings = jQuery.extend({
		allrules:allRules,
		validationEventTriggers:"blur",					
		inlineValidation: true,	
		returnIsValid:false,
		liveEvent:false,
		openDebug: true,
		unbindEngine:true,
		containerOverflow:false,
		containerOverflowDOM:"",
		ajaxSubmit: false,
		scroll:true,
		promptPosition: "topRight",	// OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight
		showTypes:1,//zrj 验证方式
		success : false,
		beforeSuccess :  function() {},
		failure : function() {}
	}, settings);	
	$.validationEngine.settings = settings;
	$.validationEngine.ajaxValidArray = [];	// ARRAY FOR AJAX: VALIDATION MEMORY 
	
	if(settings.inlineValidation === true){ 		// Validating Inline ?
		if(!settings.returnIsValid){					// NEEDED FOR THE SETTING returnIsValid
			// what the hell! orefalo
			//allowReturnIsvalid = false;
			if(settings.liveEvent){						// LIVE event, vast performance improvement over BIND
				$(this).find("[class*=validate]").live(settings.validationEventTriggers,
					function(caller){ 
						if($(caller).attr("type") != "checkbox")
							_inlinEvent(this);
					});
				$(this).find("[class*=validate][type=checkbox]").live("click", function(caller){ _inlinEvent(this); });
			}else{
				$(this).find("[class*=validate]").not("[type=checkbox]").bind(settings.validationEventTriggers, function(caller){ _inlinEvent(this); });
				$(this).find("[class*=validate][type=checkbox]").bind("click", function(caller){ _inlinEvent(this); });
			}
			
			// what the hell orefalo
			//firstvalid = false;
		}
		
		function _inlinEvent(caller){
			$.validationEngine.settings = settings;
			if($.validationEngine.intercept === false || !$.validationEngine.intercept){		// STOP INLINE VALIDATION THIS TIME ONLY
				$.validationEngine.onSubmitValid=false;
				$.validationEngine.loadValidation(caller); 
			}else{
				$.validationEngine.intercept = false;
			}
		}
	}
	if (settings.returnIsValid){		// Do validation and return true or false, it bypass everything;
		if ($.validationEngine.submitValidation(this,settings)){
			return false;
		}else{
			return true;
		}
	}
	$(this).bind("submit", function(caller){   // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY
		$.validationEngine.onSubmitValid = true;
		$.validationEngine.settings = settings;
		if($.validationEngine.submitValidation(this,settings) === false){
			if($.validationEngine.submitForm(this,settings) === true)
				return false;
		}else{
			// orefalo: what the hell is that ?
			settings.failure && settings.failure(); 
			return false;
		}		
	});
	$(".formError").live("click",function(){	 // REMOVE BOX ON CLICK
		$(this).fadeOut(150,function(){ $(this).remove(); });
	});
};	
$.validationEngine = {
	defaultSetting : function(caller) {		// NOT GENERALLY USED, NEEDED FOR THE API, DO NOT TOUCH
		if($.validationEngineLanguage){				
			allRules = $.validationEngineLanguage.allRules;
		}else{
			$.validationEngine.debug("Validation engine rules are not loaded check your external file");
		}	
		settings = {
			allrules:allRules,
			validationEventTriggers:"blur",					
			inlineValidation: true,	
			containerOverflow:false,
			containerOverflowDOM:"",
			returnIsValid:false,
			scroll:true,
			unbindEngine:true,
			ajaxSubmit: false,
			promptPosition: "topRight",	// OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight
			showTypes:1,//zrj 验证方式
			success : false,
			failure : function() {}
		};	
		$.validationEngine.settings = settings;
	},
	loadValidation : function(caller) {		// GET VALIDATIONS TO BE EXECUTED
		if(!$.validationEngine.settings)
			$.validationEngine.defaultSetting();
		var rulesParsing = $(caller).attr('class');
		var rulesRegExp = /\[(.*)\]/;
		var getRules = rulesRegExp.exec(rulesParsing);
		if(getRules === null)
			return false;
		var str = getRules[1];
		var pattern = /\[|,|\]/;
		var result= str.split(pattern);	
		var validateCalll = $.validationEngine.validateCall(caller,result);
		return validateCalll;
	},
	validateCall : function(caller,rules) {	// EXECUTE VALIDATION REQUIRED BY THE USER FOR THIS FIELD
		var promptText ="";	
		
		if(!$(caller).attr("id"))
			$.validationEngine.debug("This field have no ID attribut( name & class displayed): "+$(caller).attr("name")+" "+$(caller).attr("class"));

		// what the hell!
		//caller = caller;
		ajaxValidate = false;
		var callerName = $(caller).attr("name");
		$.validationEngine.isError = false;
		$.validationEngine.showTriangle = true;
		var callerType = $(caller).attr("type");

		for (var i=0; i<rules.length;i++){
			switch (rules[i]){
			case "optional": 
				if(!$(caller).val()){
					$.validationEngine.closePrompt(caller);
					return $.validationEngine.isError;
				}
			break;
			case "required": 
				_required(caller,rules);
			break;
			case "custom": 
				 _customRegex(caller,rules,i);
			break;
			case "exemptString": 
				 _exemptString(caller,rules,i);
			break;
			case "ajax": 
				if(!$.validationEngine.onSubmitValid)
					_ajax(caller,rules,i);	
			break;
			case "min":
			     _min(caller,rules,i);
			     break;
			case "max":
			     _max(caller,rules,i);
			     break;
			case "minSize":
			     _minSize(caller,rules,i);
			     break;
		    case "maxSize":
		         _maxSize(caller,rules,i);
		         break;
		    case "past":
		         _past(caller,rules,i);
		         break;
		    case "future":
		         _future(caller,rules,i);
		         break;
			case "length": 
				 _length(caller,rules,i);
			break;
			case "maxCheckbox": 
				_maxCheckbox(caller,rules,i);
			 	groupname = $(caller).attr("name");
			 	caller = $("input[name='"+groupname+"']");
			break;
			case "minCheckbox": 
				_minCheckbox(caller,rules,i);
				groupname = $(caller).attr("name");
			 	caller = $("input[name='"+groupname+"']");
			break;
			case "equals": 
				 _equals(caller,rules,i);
			break;
			case "funcCall": 
		     	_funcCall(caller,rules,i);
			break;
			default :
			}
		}
		radioHack();
		if ($.validationEngine.isError === true){
		    //zrj 2011-7-4 
		    if ($.validationEngine.settings.showTypes==2)
		    {
		         $.validationEngine.showMsg(caller,promptText);
		    }
		    else
		    {
			    var linkTofieldText = "." +$.validationEngine.linkTofield(caller);
			    if(linkTofieldText != "."){
				    if(!$(linkTofieldText)[0]){
					    $.validationEngine.buildPrompt(caller,promptText,"error");
				    }else{	
					    $.validationEngine.updatePromptText(caller,promptText);
				    }	
			    }else{
				    $.validationEngine.updatePromptText(caller,promptText);
			    }
			}
		}else{
		    if ($.validationEngine.settings.showTypes==2)
		    {
		       if ($.validationEngine.ajaxValid==true)
		       {
		          $(caller).removeClass("Validform_error");//移除文本框样式
		          $(caller).parent().next().find(".Validform_checktip").removeClass().addClass("Validform_checktip Validform_right").html("");//增加文本框验证通过信息
		       }
		    }
		    else
		    {
			   $.validationEngine.closePrompt(caller);
			}
		}			
		/* UNFORTUNATE RADIO AND CHECKBOX GROUP HACKS */
		/* As my validation is looping input with id's we need a hack for my validation to understand to group these inputs */
		function radioHack(){
	      if($("input[name='"+callerName+"']").size()> 1 && (callerType == "radio" || callerType == "checkbox")) {        // Hack for radio/checkbox group button, the validation go the first radio/checkbox of the group
	          caller = $("input[name='"+callerName+"'][type!=hidden]:first");     
	          $.validationEngine.showTriangle = false;
	      }      
	    }
		/* VALIDATION FUNCTIONS */
		function _required(caller,rules){   // VALIDATE BLANK FIELD
			var callerType = $(caller).attr("type");
			if (callerType == "text" || callerType == "password" || callerType == "textarea"){
								
				if(!$(caller).val()){
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}	
			}	
			if (callerType == "radio" || callerType == "checkbox" ){
				callerName = $(caller).attr("name");
		
				if($("input[name='"+callerName+"']:checked").size() === 0) {
					$.validationEngine.isError = true;
					if($("input[name='"+callerName+"']").size() == 1) {
						promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxe+"<br />"; 
					}else{
						 promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxMultiple+"<br />";
					}	
				}
			}	
			if (callerType == "select-one") { // added by paul@kinetek.net for select boxes, Thank you		
				if(!$(caller).val()) {
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}
			}
			if (callerType == "select-multiple") { // added by paul@kinetek.net for select boxes, Thank you	
				if(!$(caller).find("option:selected").val()) {
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}
			}
		}
		function _customRegex(caller,rules,position){		 // VALIDATE REGEX RULES
			var customRule = rules[position+1];
			var pattern = eval($.validationEngine.settings.allrules[customRule].regex);
			
			if(!pattern.test($(caller).attr('value'))){
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules[customRule].alertText+"<br />";
			}
		}
		function _exemptString(caller,rules,position){		 // VALIDATE REGEX RULES
			var customString = rules[position+1];
			if(customString == $(caller).attr('value')){
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules['required'].alertText+"<br />";
			}
		}
		
		function _funcCall(caller,rules,position){  
			var customRule = rules[position+1];
			var funce = $.validationEngine.settings.allrules[customRule].nname;
			var fn = window[funce];
			if (typeof(fn) === 'function'){
				var fn_result = fn();
				if(!fn_result){
					$.validationEngine.isError = true;
				}
				
				promptText += $.validationEngine.settings.allrules[customRule].alertText+"<br />";
			}
		}
		function _ajax(caller,rules,position){				 // VALIDATE AJAX RULES
			
			customAjaxRule = rules[position+1];
			postfile = $.validationEngine.settings.allrules[customAjaxRule].file;
			fieldValue = $(caller).val();
			ajaxCaller = caller;
			fieldId = $(caller).attr("id");
			ajaxValidate = true;
			ajaxisError = $.validationEngine.isError;
			
			if($.validationEngine.settings.allrules[customAjaxRule].extraData){
				extraData = $.validationEngine.settings.allrules[customAjaxRule].extraData;
			}else{
				extraData = "";
			}
			/* 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,
				   	beforeSend: function(){		// BUILD A LOADING PROMPT IF LOAD TEXT EXIST		   			
				   		if($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad){
				   		    if ($.validationEngine.settings.showTypes==2)
				   		    {
				   		         $(caller).parent().next().find(".Validform_checktip").removeClass().addClass("Validform_checktip Validform_loading").text($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad);
				   		    }
				   		    else
				   		    {
			   			        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");
 			 			        }
	 			 			}
			   			}
			  	 	},
			  	 	error: function(data,transport){ $.validationEngine.debug("error in the ajax: "+data.status+" "+transport); },
					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;
			 			 	}
				
			 			 	$.validationEngine.ajaxValid = false;
							promptText += $.validationEngine.settings.allrules[customAjaxRule].alertText+"<br />";
							if ($.validationEngine.settings.showTypes==2)
							{
							    $.validationEngine.showMsg(caller,promptText);
							}
							else
							{
							    $.validationEngine.updatePromptText(ajaxCaller,promptText,"",true);		
							}		
						 }else{	 
						 	_checkInArray(true);
						 	$.validationEngine.ajaxValid = true; 			
						 	if(!customAjaxRule)	{
						 		$.validationEngine.debug("wrong ajax response, are you on a server or in xampp? if not delete de ajax[ajaxUser] validating rule from your form ");}		   
						 	if($.validationEngine.settings.allrules[customAjaxRule].alertTextOk){	// NO OK TEXT MEAN CLOSE PROMPT	 
						 	    if ($.validationEngine.settings.showTypes==2)
				   		        {	
				   		             $(caller).removeClass("Validform_error");//移除文本框样式
		                             $(caller).parent().next().find(".Validform_checktip").removeClass().addClass("Validform_checktip Validform_right").html("");//增加文本框验证通过信息
				   		        }
				   		        else
				   		        {		
	 			 				    $.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextOk,"pass",true);
	 			 	            }
 			 				}else{
				 			 	ajaxValidate = false;		 	
				 			 	$.validationEngine.closePrompt(ajaxCaller);
 			 				}		
			 			 }
			 			function  _checkInArray(validate){
			 				for(var x=0 ;x<ajaxErrorLength;x++){
			 			 		if($.validationEngine.ajaxValidArray[x][0] == fieldId){
			 			 			$.validationEngine.ajaxValidArray[x][1] = validate;
			 			 			existInarray = true;
			 			 		}
			 			 	}
			 			}
			 		}				
				});
			}
		}
		function _equals(caller,rules,position){		 // VALIDATE FIELD MATCH
			var equalsField = rules[position+1];
			
			if($(caller).attr('value') != $("#"+equalsField).attr('value')){
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules["equals"].alertText+"<br />";
			}
		}
		function _length(caller,rules,position){    	  // VALIDATE LENGTH
			var startLength = eval(rules[position+1]);
			var endLength = eval(rules[position+2]);
			var feildLength = $(caller).attr('value').length;

			if(feildLength<startLength || feildLength>endLength){
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules["length"].alertText+startLength+$.validationEngine.settings.allrules["length"].alertText2+endLength+$.validationEngine.settings.allrules["length"].alertText3+"<br />";
			}
		}
		function _minSize(caller,rules,position){
		    var min = rules[position+1];
		    var len = $(caller).val().length;
		    if (len < min){
		        $.validationEngine.isError = true;
		        promptText +=$.validationEngine.settings.allrules["minSize"].alertText + min + $.validationEngine.settings.allrules["minSize"].alertText2+"<br />";
		    }
		}
		function _maxSize(caller,rules,position){
		    var max=rules[position+1];
		    var len=$(caller).val().length;
		    if (len > max)
		    {
		        $.validationEngine.isError = true;
		        var rule=$.validationEngine.settings.allrules["maxSize"];
		        promptText +=rule.alertText + max + rule.alertText2 + "<br />";
		    }
		}
		function _min(caller,rules,position){
		    var min=parseFloat(rules[position+1]);
		    var len=parseFloat($(caller).val());
		    if (len < min )
		    {
		        $.validationEngine.isError = true;
		        var rule=$.validationEngine.settings.allrules["min"];
		        if (rule.alertText2)
		           promptText +=rule.alertText + min + rule.alertText2+"<br />";
		        promptText +=rule.alertText+min +"<br />"
		    }
		}
		function _max(caller,rules,position){
		     var max=parseFloat(rules[position +1]);
		     var len=parseFloat($(caller).val());
		     if (len >max)
		     {
		         $.validationEngine.isError = true;
		         var rule=$.validationEngine.settings.allrules["max"];
		         if (rule.alertText2)
		           promptText +=rule.alertText + min + rule.alertText2+"<br />";
		         promptText +=rule.alertText+max +"<br />"
		     }
		}
		function _past(caller,rules,position){
		     var p=rules[position+1];
		     var pdate=(p.toLowerCase()=="now")?new Date():_parseDate(p);
		     var vdate=_parseDate($(caller).val());
		     if (vdate <pdate)
		     {
		         $.validationEngine.isError = true;
		         var rule=$.validationEngine.settings.allrules["past"];
		        if (rule.alertText2) 
		           promptText += rule.alertText + _dateToString(pdate) + rule.alertText2+"<br />";
                promptText += rule.alertText + _dateToString(pdate)+"<br />";
		     }
		}
		function  _future(caller, rules, position) {
            var p=rules[position + 1];
            var pdate = (p.toLowerCase() == "now")? new Date(): _parseDate(p);
            var vdate = _parseDate($(caller).val());

            if (vdate > pdate ) {
                var rule = options.allrules.future;
                if (rule.alertText2)  promptText += rule.alertText + _dateToString(pdate) + rule.alertText2+"<br />";
                 promptText += rule.alertText + _dateToString(pdate)+"<br />";
            }
        }
        function _dateToString(date) {

            return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
        }
        /**
         * Parses an ISO date
         * @param {String} d
         */
        function _parseDate(d) {

            var dateParts = d.split("-");
            if(dateParts==d)
                dateParts = d.split("/");
            return new Date(dateParts[0], (dateParts[1] - 1) ,dateParts[2]);
        }
		function _maxCheckbox(caller,rules,position){  	  // VALIDATE CHECKBOX NUMBER
		
			var nbCheck = eval(rules[position+1]);
			var groupname = $(caller).attr("name");
			var groupSize = $("input[name='"+groupname+"']:checked").size();
			if(groupSize > nbCheck){	
				$.validationEngine.showTriangle = false;
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules["maxCheckbox"].alertText+"<br />";
			}
		}
		function _minCheckbox(caller,rules,position){  	  // VALIDATE CHECKBOX NUMBER
		
			var nbCheck = eval(rules[position+1]);
			var groupname = $(caller).attr("name");
			var groupSize = $("input[name='"+groupname+"']:checked").size();
			if(groupSize < nbCheck){	
			
				$.validationEngine.isError = true;
				$.validationEngine.showTriangle = false;
				promptText += $.validationEngine.settings.allrules["minCheckbox"].alertText+" "+nbCheck+" "+$.validationEngine.settings.allrules["minCheckbox"].alertText2+"<br />";
			}
		}
		return ($.validationEngine.isError) ? $.validationEngine.isError : false;
	},
	submitForm : function(caller){
		if ($.validationEngine.settings.success) {	// AJAX SUCCESS, STOP THE LOCATION UPDATE
			if($.validationEngine.settings.unbindEngine) $(caller).unbind("submit");
			var serializedForm = $(caller).serialize();
			$.validationEngine.settings.success && $.validationEngine.settings.success(serializedForm);
			return true;
		}
		return false;
	},
	showMsg: function (caller,promptText)
	{
	    if(!$.validationEngine.settings) {
			$.validationEngine.defaultSetting();
		}
		if (promptText !="")
		{
		    var str=promptText.split("<br />");
		    if (str.length>1)
		    {
		        promptText=str[str.length-2];
		    }
		    else
		    {
		        promptText=str[0];
		    }
		}
		$(caller).addClass("Validform_error");
		$(caller).parent().next().find(".Validform_checktip").removeClass().addClass("Validform_wrong Validform_checktip").text(promptText);
	},
	buildPrompt : function(caller,promptText,type,ajaxed) {		// ERROR PROMPT CREATION AND DISPLAY WHEN AN ERROR OCCUR
		if(!$.validationEngine.settings) {
			$.validationEngine.defaultSetting();
		}
		var deleteItself = "." + $(caller).attr("id") + "formError";
		
	    //$("#"+tx).attr("style",";border-color:Red;");
		if($(deleteItself)[0]) {
			$(deleteItself).stop();
			$(deleteItself).remove();
		}
		var divFormError = document.createElement('div');
		var formErrorContent = document.createElement('div');
		var linkTofield = $.validationEngine.linkTofield(caller);
		$(divFormError).addClass("formError");
		
		if(type == "pass")
			$(divFormError).addClass("greenPopup");
		if(type == "load")
			$(divFormError).addClass("blackPopup");
		if(ajaxed)
			$(divFormError).addClass("ajaxed");
		
		$(divFormError).addClass(linkTofield);
		$(formErrorContent).addClass("formErrorContent");
		
		if($.validationEngine.settings.containerOverflow)		// Is the form contained in an overflown container?
			$(caller).before(divFormError);
		else
			$("body").append(divFormError);
				
		$(divFormError).append(formErrorContent);
			
		if($.validationEngine.showTriangle != false){		// NO TRIANGLE ON MAX CHECKBOX AND RADIO
			var arrow = document.createElement('div');
			$(arrow).addClass("formErrorArrow");
			$(divFormError).append(arrow);
			if($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight") {
				$(arrow).addClass("formErrorArrowBottom");
				$(arrow).html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
			}
			else if($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight"){
				$(divFormError).append(arrow);
				$(arrow).html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
			}
		}
		$(formErrorContent).html(promptText);
		
		var calculatedPosition = $.validationEngine.calculatePosition(caller,promptText,type,ajaxed,divFormError);
		calculatedPosition.callerTopPosition +="px";
		calculatedPosition.callerleftPosition +="px";
		calculatedPosition.marginTopSize +="px";
	    if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {   
           $(divFormError).append('<iframe class="iframe" frameborder="0" scr="javascript:false;"></iframe>');   
        }   

		$(divFormError).css({
			"top":calculatedPosition.callerTopPosition,
			"left":calculatedPosition.callerleftPosition,
			"marginTop":calculatedPosition.marginTopSize,
			"opacity":0
		});
		//orefalo - what the hell
		//return $(divFormError).animate({"opacity":0.87},function(){return true;});
		return $(divFormError).animate({"opacity":0.87});	
	},
	updatePromptText : function(caller,promptText,type,ajaxed) {	// UPDATE TEXT ERROR IF AN ERROR IS ALREADY DISPLAYED
		
		var linkTofield = $.validationEngine.linkTofield(caller);
		var updateThisPrompt =  "."+linkTofield;
		
		if(type == "pass")
			$(updateThisPrompt).addClass("greenPopup");
		else
			$(updateThisPrompt).removeClass("greenPopup");
		
		if(type == "load")
			$(updateThisPrompt).addClass("blackPopup");
		else
			$(updateThisPrompt).removeClass("blackPopup");
		
		if(ajaxed)
			$(updateThisPrompt).addClass("ajaxed");
		else
			$(updateThisPrompt).removeClass("ajaxed");
	
		$(updateThisPrompt).find(".formErrorContent").html(promptText);
		
		var calculatedPosition = $.validationEngine.calculatePosition(caller,promptText,type,ajaxed,updateThisPrompt);
		calculatedPosition.callerTopPosition +="px";
		calculatedPosition.callerleftPosition +="px";
		calculatedPosition.marginTopSize +="px";
		$(updateThisPrompt).animate({ "top":calculatedPosition.callerTopPosition,"marginTop":calculatedPosition.marginTopSize });
	},
	calculatePosition : function(caller,promptText,type,ajaxed,divFormError){
		
		var callerTopPosition,callerleftPosition,inputHeight,marginTopSize;
		var callerWidth =  $(caller).width();
		
		if($.validationEngine.settings.containerOverflow){		// Is the form contained in an overflown container?
			callerTopPosition = 0;
			callerleftPosition = 0;
			inputHeight = $(divFormError).height();					// compasation for the triangle
			marginTopSize = "-"+inputHeight;
		}else{
			callerTopPosition = $(caller).offset().top;
			callerleftPosition = $(caller).offset().left;
			inputHeight = $(divFormError).height();
			marginTopSize = 0;
		}
		
		/* POSITIONNING */
		if($.validationEngine.settings.promptPosition == "topRight"){ 
			if($.validationEngine.settings.containerOverflow){		// Is the form contained in an overflown container?
				callerleftPosition += callerWidth -30;
			}else{
				callerleftPosition +=  callerWidth -30; 
				callerTopPosition += -inputHeight; 
			}
		}
		if($.validationEngine.settings.promptPosition == "topLeft"){ callerTopPosition += -inputHeight -10; }
		
		if($.validationEngine.settings.promptPosition == "centerRight"){ callerleftPosition +=  callerWidth +13; }
		
		if($.validationEngine.settings.promptPosition == "bottomLeft"){
			callerTopPosition = callerTopPosition + $(caller).height() + 15;
		}
		if($.validationEngine.settings.promptPosition == "bottomRight"){
			callerleftPosition +=  callerWidth -30;
			callerTopPosition +=  $(caller).height() +5;
		}
		return {
			"callerTopPosition":callerTopPosition,
			"callerleftPosition":callerleftPosition,
			"marginTopSize":marginTopSize
		};
	},
	linkTofield : function(caller){
		var linkTofield = $(caller).attr("id") + "formError";
		linkTofield = linkTofield.replace(/\[/g,""); 
		linkTofield = linkTofield.replace(/\]/g,"");
		return linkTofield;
	},
	closePrompt : function(caller,outside) {						// CLOSE PROMPT WHEN ERROR CORRECTED
		if(!$.validationEngine.settings){
			$.validationEngine.defaultSetting();
		}
		if(outside){
			$(caller).fadeTo("fast",0,function(){
				$(caller).remove();
			});
			return false;
		}
		
		// orefalo -- review conditions non sense
		if(typeof(ajaxValidate)=='undefined')
		{ ajaxValidate = false; }
		if(!ajaxValidate){
			var linkTofield = $.validationEngine.linkTofield(caller);
			var closingPrompt = "."+linkTofield;
			$(closingPrompt).fadeTo("fast",0,function(){
				$(closingPrompt).remove();
			});
		}
	},
	debug : function(error) {
		if(!$.validationEngine.settings.openDebug) return false;
		if(!$("#debugMode")[0]){
			$("body").append("<div id='debugMode'><div class='debugError'><strong>This is a debug mode, you got a problem with your form, it will try to help you, refresh when you think you nailed down the problem</strong></div></div>");
		}
		$(".debugError").append("<div class='debugerror'>"+error+"</div>");
	},			
	submitValidation : function(caller) {			// FORM SUBMIT VALIDATION LOOPING INLINE VALIDATION
	    if(!$.validationEngine.settings) {
			$.validationEngine.defaultSetting();
		}
		var stopForm = false;
		//$.validationEngine.ajaxValid = true;
		var toValidateSize = $(caller).find("[class*=validate]").size();
		 $(caller).find("[class*=validate]").each(function(){
			var linkTofield = $.validationEngine.linkTofield(this);
			
			if(!$("."+linkTofield).hasClass("ajaxed")){	// DO NOT UPDATE ALREADY AJAXED FIELDS (only happen if no normal errors, don't worry)
				var validationPass = $.validationEngine.loadValidation(this);
				return(validationPass) ? stopForm = true : "";					
			};
		    });
		var ajaxErrorLength = $.validationEngine.ajaxValidArray.length;		// LOOK IF SOME AJAX IS NOT VALIDATE
		for(var x=0;x<ajaxErrorLength;x++){
	 		if($.validationEngine.ajaxValidArray[x][1] == false)
	 			$.validationEngine.ajaxValid = false;
 		}
	    if ($.validationEngine.settings.showTypes==2)
	    {
		    if (stopForm || !$.validationEngine.ajaxValid)
		    {
		        return true;
		    }
		    else
		    {
		       return false;
		    }
	    }
	    else
	    {
		if(stopForm || !$.validationEngine.ajaxValid){		// GET IF THERE IS AN ERROR OR NOT FROM THIS VALIDATION FUNCTIONS
			if($.validationEngine.settings.scroll){
				if(!$.validationEngine.settings.containerOverflow){
					var destination = $(".formError:not('.greenPopup'):first").offset().top;
					$(".formError:not('.greenPopup')").each(function(){
						var testDestination = $(this).offset().top;
						if(destination>testDestination)
							destination = $(this).offset().top;
					});
					$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100);
				}else{
					var destination = $(".formError:not('.greenPopup'):first").offset().top;
					var scrollContainerScroll = $($.validationEngine.settings.containerOverflowDOM).scrollTop();
					var scrollContainerPos = - parseInt($($.validationEngine.settings.containerOverflowDOM).offset().top);
					destination = scrollContainerScroll + destination + scrollContainerPos -5;
					var scrollContainer = $.validationEngine.settings.containerOverflowDOM+":not(:animated)";
					
					$(scrollContainer).animate({ scrollTop: destination}, 1100);
				}
			}
			return true;
		}else{
			return false;
		}
		}
	}
};
})(jQuery);
posted @ 2011-07-11 17:18  zrj531  阅读(5972)  评论(2编辑  收藏  举报