jValidate.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. (function($){
  2. /**
  3. * Define global and singleton object jValidation
  4. */
  5. var jValidation = $.jValidation || {};
  6. var Tips = $.Tips || {};
  7. /**
  8. * Define class ajax.Result for ajax validation
  9. * @returns {jValidation.ajax.Result}
  10. */
  11. jValidation.ajax = {
  12. Result:function(){}
  13. };
  14. jValidation.ajax.Result.prototype = {
  15. result : undefined,
  16. errorMsg:undefined,
  17. errorCode:undefined,
  18. setErrorMsg:function(errorMsg){
  19. this.errorMsg = errorMsg;
  20. },
  21. setErrorCode:function(errorCode){
  22. this.errorCode = errorCode;
  23. },
  24. setResult:function(result){
  25. this.result = result;
  26. }
  27. };
  28. jValidation.ValidationDefaultOptions = function(){};
  29. jValidation.ValidationDefaultOptions.prototype = {
  30. //是否监听form的submit事件
  31. onSubmit : true,
  32. //是否监听form的reset事件
  33. onReset : true,
  34. //表单验证时停留在第一个验证的地方,不继续验证下去
  35. stopOnFirst : false,
  36. //是否实时检查数据的合法性
  37. immediate : false,
  38. //是否出错时将光标指针移到出错的输入框上
  39. focusOnError : false,
  40. //是否使用input的title属性作为出错时的提示信息
  41. useTitles : false,
  42. //Form验证时的回调函数,可以修改最终的返回结果
  43. onFormValidate : function(result, form) {return result;},
  44. //某个input验证时的回调函数
  45. onElementValidate : function(result, elm) {},
  46. //用于ajax验证回调
  47. onElementValidateForAjax:function(elm){}
  48. };
  49. //是否开启tips错误提示
  50. jValidation.Tips = {
  51. useTips:true,
  52. showArrow:true,
  53. position:'right'
  54. };
  55. jValidation.ValidatorDefaultOptions = function(){};
  56. jValidation.ValidatorDefaultOptions.prototype = {
  57. ignoreEmptyValue : true, //是否忽略空值
  58. depends : [] //相关依赖项
  59. };
  60. /**
  61. * Define jValidation util obj
  62. */
  63. jValidation.util = {
  64. rclass : /[\n\t]/g,
  65. hasClass : function(dom, className)
  66. {
  67. //Codes below come form jQuery-1.4.4 jQuery.fn.hasClass().
  68. var className = " " + className + " ";
  69. return dom.className && ((" " + dom.className + " ").replace(this.rclass, " ").indexOf( className ) > -1);
  70. },
  71. stop: function(event) {
  72. if (event.preventDefault) {
  73. event.preventDefault();
  74. event.stopPropagation();
  75. } else {
  76. event.returnValue = false;
  77. event.cancelBubble = true;
  78. }
  79. },
  80. getElementLeft: function (element){
  81. var actualLeft = element.offsetLeft;
  82. var current = element.offsetParent;
  83. while (current !== null){
  84. actualLeft += current.offsetLeft;
  85. current = current.offsetParent;
  86. }
  87. return actualLeft;
  88. },
  89. getElementTop: function (element){
  90. var actualTop = element.offsetTop;
  91. var current = element.offsetParent;
  92. while (current !== null){
  93. actualTop += current.offsetTop;
  94. current = current.offsetParent;
  95. }
  96. return actualTop;
  97. },
  98. toArrayByArgus:function(arguments){
  99. // return a array
  100. return Array.prototype.slice.call(arguments);
  101. },
  102. visible: function(element) {
  103. return $(element).css("display") != 'none';
  104. },
  105. isVisible : function(elm) {
  106. while(elm && elm.tagName != 'BODY') {
  107. if(!this.visible(elm)) return false;
  108. elm = elm.parentNode;
  109. }
  110. return true;
  111. },
  112. getInputValue : function(elm) {
  113. var jElm = $(elm);
  114. return jElm.val();
  115. },
  116. // 通过classname传递的参数必须通过'-'分隔各个参数
  117. // 返回值包含一个参数singleArgument,例:validate-pattern-/[a-c]/gi,singleArgument值为/[a-c]/gi
  118. getArgumentsByClassName : function(prefix,className) {
  119. if(!className || !prefix)
  120. return [];
  121. var pattern = new RegExp(prefix+'-(\\S+)');
  122. var matchs = className.match(pattern);
  123. if(!matchs)
  124. return [];
  125. var results = [];
  126. results.singleArgument = matchs[1];
  127. var args = matchs[1].split('-');
  128. for(var i = 0; i < args.length; i++) {
  129. if(args[i] == '') {
  130. if(i+1 < args.length) args[i+1] = '-'+args[i+1];
  131. }else{
  132. results.push(args[i]);
  133. }
  134. }
  135. return results;
  136. },
  137. getFormElements: function(jForm){
  138. return jForm.find(":text,:password,:radio.validate-one-required,:checkbox[class*=checkbox-required],select,textarea,.j-radio-wrapper,.j-checkbox-wrapper,[data-type=comboSelect]");
  139. },
  140. format : function(str,args) {
  141. args = args || [];
  142. jValidation.util.assert(args.constructor == Array,"jValidation.util.format() arguement 'args' must is Array");
  143. var result = str;
  144. for (var i = 0; i < args.length; i++){
  145. result = result.replace(/%s/, args[i]);
  146. }
  147. return result;
  148. },
  149. assert : function(condition,message) {
  150. var errorMessage = message || ("assert failed error,condition="+condition);
  151. if (!condition) {
  152. alert(errorMessage);
  153. throw new Error(errorMessage);
  154. }else {
  155. return condition;
  156. }
  157. },
  158. isDate : function(v,dateFormat,elm,isdateinput) {
  159. //TODO CYC 201604158 isdateinput是否日期控件验证
  160. var MONTH = "MM";
  161. var DAY = "dd";
  162. var YEAR = "yyyy";
  163. var regex = '^'+dateFormat.replace(YEAR,'\\d{4}').replace(MONTH,'\\d{2}').replace(DAY,'\\d{2}')+'$';
  164. //TODO CYC 201604158
  165. if(isdateinput=="1"){
  166. var dateF2="yyyyMMdd";
  167. var regex1= '^'+dateF2.replace(YEAR,'\\d{4}').replace(MONTH,'\\d{2}').replace(DAY,'\\d{2}')+'$';
  168. if(new RegExp(regex1).test(v)){
  169. v= v.substr(0,4)+"-"+v.substr(4,2)+"-"+v.substr(6,2)
  170. $(elm).val(v)
  171. }
  172. }
  173. if(!new RegExp(regex).test(v)) return false;
  174. var year = v.substr(dateFormat.indexOf(YEAR),4);
  175. var month = v.substr(dateFormat.indexOf(MONTH),2);
  176. var day = v.substr(dateFormat.indexOf(DAY),2);
  177. var d = new Date(jValidation.util.format('%s/%s/%s',[year,month,day]));
  178. return ( parseInt(month, 10) == (1+d.getMonth()) ) &&
  179. (parseInt(day, 10) == d.getDate()) &&
  180. (parseInt(year, 10) == d.getFullYear() );
  181. },
  182. getElmID : function(elm) {
  183. var reg = /[\[\]\.\{\}]/g;
  184. // TODO [代码片段001][修正被校验控件没有id和name时,出现的抛错问题][yezehua]
  185. if(!$(elm).attr("id") && !$(elm).attr("name")) return "";
  186. // TODO [代码片段001][修正被校验控件没有id和name时,出现的抛错问题][yezehua] 结束
  187. return $(elm).attr("id") ? $(elm).attr("id") : $(elm).attr("name").replace(reg,"");
  188. },
  189. getLanguage : function() {
  190. var lang = null;
  191. if (typeof navigator.userLanguage == 'undefined')
  192. lang = navigator.language.toLowerCase();
  193. else
  194. lang = navigator.userLanguage.toLowerCase();
  195. return lang;
  196. },
  197. getMessageSource : function() {
  198. var lang = jValidation.util.getLanguage();
  199. var messageSource = jValidation.Validator.messageSource['zh-cn'];
  200. if(jValidation.Validator.messageSource[lang]) {
  201. messageSource = jValidation.Validator.messageSource[lang];
  202. }
  203. var results = {};
  204. for(var i = 0; i < messageSource.length; i++) {
  205. results[messageSource[i][0]] = messageSource[i][1];
  206. }
  207. return results;
  208. },
  209. getI18nMsg : function(key) {
  210. return jValidation.util.getMessageSource()[key];
  211. }
  212. };
  213. /**
  214. * Define class Validator
  215. */
  216. jValidation.Validator = function(className,test,options){
  217. this.init(className,test,options);
  218. };
  219. //define Validator messageSource
  220. jValidation.Validator.messageSource = {};
  221. jValidation.Validator.messageSource['zh-cn'] = [
  222. ['validation-failed' , '验证失败.'],
  223. ['required' , '该项目为必添项,不允许为空!'],
  224. ['validate-number' , '请输入有效的数字.'],
  225. ['validate-digits' , '请输入数字.'],
  226. ['validate-positive-integer' , '请输入正整数'],
  227. ['validate-alpha' , '请输入英文字母.'],
  228. ['validate-alphanum' , '请输入英文字母或是数字,其它字符是不允许的.'],
  229. ['validate-email' , '请输入有效的邮件地址,如 username@example.com.'],
  230. ['validate-url' , '请输入有效的URL地址.'],
  231. ['validate-currency-dollar' , 'Please enter a valid $ amount. For example $100.00 .'],
  232. ['validate-one-required' , '在前面选项至少选择一个.'],
  233. ['validate-integer' , '请输入正确的整数'],
  234. ['validate-pattern' , '输入的值不匹配'],
  235. ['validate-ip','请输入正确的IP地址'],
  236. ['min-value' , '最小值为%s'],
  237. ['max-value' , '最大值为%s'],
  238. ['min-length' , '最小长度为%s,当前长度为%s.'],
  239. ['max-length', '最大长度为%s,当前长度为%s.'],
  240. ['int-range' , '输入值应该为 %s 至 %s 的整数'],
  241. ['float-range' , '输入值应该为 %s 至 %s 的数字'],
  242. ['length-range' , '输入值的长度应该在 %s 至 %s 之间,当前长度为%s'],
  243. ['equals','两次输入不一致,请重新输入!'],
  244. ['less-than','请输入小于前面的值'],
  245. ['less-than-equal','请输入小于或等于前面的值'],
  246. ['great-than','请输入大于前面的值'],
  247. ['great-than-equal','请输入大于或等于前面的值'],
  248. //['validate-date' , '请输入有效的日期,格式为 %s. 例如:%s.'],
  249. /*TODO 20160415 cyc 格式省略*/
  250. ['validate-date' , '请输入有效的日期,例如:2006-03-12'],
  251. ['validate-selection' , '请选择.'],
  252. ['validate-file' , function(v,elm,args,metadata) {
  253. return jValidation.util.format("文件类型应该为[%s]其中之一",[args.join(',')]);
  254. }],
  255. ['validate-id-number','请输入合法的身份证号码'],
  256. ['validate-chinese','请输入中文'],
  257. ['validate-phone','请输入正确的电话号码,如:010-29392929,当前长度为%s.'],
  258. ['validate-mobile-phone','请输入正确的手机号码,当前长度为%s.'],
  259. ['validate-zip','请输入有效的邮政编码'],
  260. ['validate-qq','请输入有效的QQ号码.'],
  261. ['validate-devid','设备输入ID有误'],
  262. ['validate-space','不能输入空格!'],
  263. ['checkbox-required','至少勾选1个'],
  264. ['validate-money','请输入正确的数值,最高保留2位小数'],
  265. ['validate-contact-way','请输入有效的电话号码或手机号码'],
  266. ['validate-org-length','请选择到医院一级!'],
  267. ['validate-org-code','请输入正确的组织代码格式,如:46650460-X'],
  268. ['validate-special-char','不允许输入 \' 符号']
  269. ];
  270. jValidation.Validator.prototype = {
  271. //init method
  272. init: function(className,test,options){
  273. this.options = $.extend(new jValidation.ValidatorDefaultOptions(), options || {});
  274. this._test = test ? test : function(v,elm){ return true ;};
  275. this._error = jValidation.util.getI18nMsg(className) ? jValidation.util.getI18nMsg(className) : jValidation.util.getI18nMsg('validation-failed');
  276. this.className = className;
  277. },
  278. _dependsTest : function(v,elm) {
  279. if(this.options.depends && this.options.depends.length > 0) {
  280. var dependsResult = $A(this.options.depends).all(function(depend){
  281. return jValidation.Validation.get(depend).test(v,elm);
  282. });
  283. return dependsResult;
  284. }
  285. return true;
  286. },
  287. testAndGetError : function(v, elm,useTitle) {
  288. var dependsError = this.testAndGetDependsError(v,elm);
  289. if(dependsError) return dependsError;
  290. if(!elm) elm = {};
  291. var isEmpty = (this.options.ignoreEmptyValue && ((v == null) || (v.length == 0)));
  292. var result = isEmpty || this._test(v,elm,jValidation.util.getArgumentsByClassName(this.className,elm.className),this);
  293. if(!result) return this.error(v,elm,useTitle);
  294. return null;
  295. },
  296. testAndGetDependsError : function(v,elm) {
  297. var depends = this.options.depends;
  298. if(depends && depends.length > 0) {
  299. for(var i = 0; i < depends.length; i++) {
  300. var dependsError = jValidation.Validation.get(depends[i]).testAndGetError(v,elm);
  301. if(dependsError) return dependsError;
  302. }
  303. }
  304. return null;
  305. },
  306. /*
  307. * 返回验证错误提示信息
  308. */
  309. error : function(v,elm,useTitle) {
  310. var args = jValidation.util.getArgumentsByClassName(this.className,elm.className);
  311. var error = this._error;
  312. if(typeof error == 'string') {
  313. if(v) args.push(v.length);
  314. error = jValidation.util.format(this._error,args);
  315. }else if(typeof error == 'function') {
  316. error = error(v,elm,args,this);
  317. }else {
  318. alert('property "_error" must type of string or function,current type:'+typeof error+" current className:"+this.className);
  319. }
  320. //判断是否使用了useTitle
  321. useTitle = jValidation.util.hasClass(elm,'useTitle');
  322. if(useTitle){
  323. if(elm){
  324. var titleName = this.className+"-title";
  325. if(elm.getAttribute(titleName)){
  326. var titleErrorMsg = elm.getAttribute(titleName);
  327. return titleErrorMsg;
  328. }
  329. }
  330. }
  331. return error;
  332. }
  333. };
  334. /**
  335. * Define Class and its constructor: Validation
  336. */
  337. jValidation.Validation = function(jForm,options){
  338. this.init(jForm,options);
  339. return this;
  340. };
  341. jValidation.Validation.prototype = {
  342. init: function(jForm,options){
  343. this.options = $.extend(true,new jValidation.ValidationDefaultOptions(),options);
  344. this.jForm = jForm;
  345. if(this.options.immediate) {
  346. var useTitles = this.options.useTitles;
  347. var callback = this.options.onElementValidate;
  348. var ajaxCallback = this.options.onElementValidateForAjax;
  349. var elements =jValidation.util.getFormElements(jForm);
  350. elements.each(function(){
  351. $(this).bind('blur', function(event){
  352. jValidation.Validation.validateElement(event.target || event.srcElement, {
  353. useTitle: useTitles,
  354. onElementValidate: callback,
  355. onElementValidateForAjax:ajaxCallback
  356. });
  357. });
  358. if($(this).prop("tagName").toLowerCase() == 'select'){
  359. $(this).bind('change', function(event){
  360. jValidation.Validation.reset(event.target || event.srcElement);
  361. });
  362. }else if(this.type && (this.type.toLowerCase() == 'checkbox' || this.type.toLowerCase() == 'radio')){
  363. var that = this;
  364. $(this).parent().find(":input").each(function(){
  365. $(this).click(function(){
  366. jValidation.Validation.resetCheckbox(that);
  367. });
  368. });
  369. }
  370. else{
  371. $(this).bind('keydown', function(event){
  372. jValidation.Validation.reset(event.target || event.srcElement);
  373. });
  374. }
  375. });
  376. }
  377. },
  378. onSubmit : function(ev){
  379. if(!this.validate()) jValidation.util.stop(ev);
  380. },
  381. validate : function() {
  382. //TODO
  383. var result = true;
  384. var useTitles = this.options.useTitles;
  385. var callback = this.options.onElementValidate;
  386. var ajaxCallback = this.options.onElementValidateForAjax;
  387. //解决弹出div验证问题,弹出关闭后jForm对象可能改变,采用id重新获取
  388. if(this.jForm.attr("id")){
  389. var id =this.jForm.attr("id");
  390. this.jForm = $("#"+id);
  391. }
  392. var jElements =jValidation.util.getFormElements(this.jForm);
  393. //stop validator on fires err element
  394. if(this.options.stopOnFirst) {
  395. for(var i = 0; i < jElements.size(); i++) {
  396. var elm = jElements[i];
  397. result = jValidation.Validation.validateElement(elm,{useTitle : useTitles, onElementValidate : callback,onElementValidateForAjax:ajaxCallback});
  398. if(!result) break;
  399. }
  400. } else {
  401. for(var i = 0; i < jElements.size(); i++) {
  402. var elm = jElements[i];
  403. if(!jValidation.Validation.validateElement(elm,{useTitle : useTitles, onElementValidate : callback,onElementValidateForAjax:ajaxCallback})) {
  404. result = false;
  405. }
  406. }
  407. }
  408. // focusOnError
  409. if(!result && this.options.focusOnError) {
  410. var first = null;
  411. jElements.each(function(){
  412. if(jValidation.util.hasClass(this,"validation-failed")){
  413. first = this;
  414. return false;
  415. }
  416. });
  417. if(first.select) first.select();
  418. first.focus();
  419. }
  420. return this.options.onFormValidate(result, this.jForm);
  421. },
  422. reset : function() {
  423. var jElements =jValidation.util.getFormElements(this.jForm);
  424. jElements.each(function(){
  425. jValidation.Validation.reset(this);
  426. });
  427. }
  428. };
  429. /**
  430. * Define Class Validation static method
  431. */
  432. $.extend(true,jValidation.Validation,{
  433. validateElement : function(elm, options)
  434. {
  435. options = $.extend({useTitle : false,
  436. onElementValidate : function(result, elm) {}},options || {});
  437. if(elm.className){
  438. var cn = elm.className.split(/\s+/);
  439. //TODO
  440. for(var i = 0; i < cn.length; i++) {
  441. var cssName = cn[i];
  442. //for ajax validation
  443. if(cssName == 'ajax'){
  444. var result = options.onElementValidateForAjax(elm);
  445. if(result instanceof jValidation.ajax.Result){
  446. if(!result.result){
  447. var errorMsg = result.errorMsg;
  448. jValidation.Validation.showErrorMsg(cssName,elm,errorMsg);
  449. return false;
  450. }
  451. }
  452. // for general validation
  453. }else{
  454. var test = this.test(cssName,elm,options.useTitle);
  455. options.onElementValidate(test, cssName);
  456. if(test) {
  457. jValidation.Validation.reset(elm);
  458. } else {
  459. return false;
  460. }
  461. }
  462. }
  463. }
  464. //is show successed info
  465. //去除绿色钩钩
  466. //jValidation.Validation.showSuccessMsg("successed",elm);
  467. return true;
  468. },
  469. test : function(cssName, elm, useTitle) {
  470. var Validation = jValidation.Validation;
  471. var v = this.get(cssName);
  472. var errorMsg = null;
  473. if($(elm).hasClass('force-validate') || jValidation.util.isVisible(elm))
  474. errorMsg = v.testAndGetError(jValidation.util.getInputValue(elm),elm,useTitle);
  475. if(errorMsg) {
  476. Validation.showErrorMsg(cssName,elm,errorMsg);
  477. return false;
  478. } else {
  479. Validation.hideErrorMsg(cssName,elm);
  480. return true;
  481. }
  482. },
  483. showErrorMsg : function(name,elm,errorMsg) {
  484. this.reset(elm);
  485. //change to jquery object
  486. var jElm = $(elm);
  487. if(jValidation.Tips.useTips){
  488. Tips.tip($(elm),{content:errorMsg,position:jValidation.Tips.position,showArrow:jValidation.Tips.showArrow});
  489. if(elm.type && (elm.type.toLowerCase() == 'radio' || elm.type.toLowerCase() == 'checkbox')){
  490. jElm.parent().hasClass("validation-failed-span")?"":jElm.wrap('<span class="validation-failed-span"></span>');
  491. }
  492. }else{
  493. var prop = jValidation.Validation._getAdviceProp(name);
  494. var advice = jValidation.Validation.getAdvice(name, elm);
  495. if(!jElm.attr(prop)) {
  496. //Judgment is assign advice position, if not then create a advice
  497. if(advice.size()==0) {
  498. advice = jValidation.Validation.newErrorMsgAdvice(name,elm,errorMsg);
  499. //chage to jquery object
  500. advice = $(advice);
  501. }
  502. }
  503. if(advice && !jValidation.util.isVisible(advice[0])) {
  504. advice.css("display",'');
  505. }
  506. advice.html(errorMsg);
  507. jElm.attr(prop,true);
  508. }
  509. var $wrap = jElm.closest('.j-text-wrapper');
  510. if($wrap.length) {
  511. $wrap.removeClass('validation-passed');
  512. $wrap.addClass('validation-failed');
  513. } else {
  514. jElm.removeClass('validation-passed');
  515. jElm.addClass('validation-failed');
  516. }
  517. },
  518. showSuccessMsg : function(name,elm) {
  519. this.reset(elm);
  520. var jElm = $(elm);
  521. //var prop = jValidation.Validation._getAdviceProp(name);
  522. var advice = jValidation.Validation.getAdvice(name, elm);
  523. //if(!jElm.attr(prop)) {
  524. //判断是否已经自动指定advice位置了,如果没有则创建
  525. if(advice.size() == 0) {
  526. advice = jValidation.Validation.newSuccessMsgAdvice(name,elm);
  527. advice = $(advice);
  528. //自定义了提示信息位置的情况
  529. }else{
  530. advice.removeClass("validation-advice");
  531. advice.addClass("validation-success-advice");
  532. advice.html("");
  533. advice.show();
  534. }
  535. //}
  536. //jElm.attr(prop,true);
  537. //jElm.addClass('validation-passed');
  538. //jElm.removeClass('validation-failed');
  539. var $wrap = jElm.closest('.j-text-wrapper');
  540. if($wrap.length) {
  541. $wrap.addClass('validation-passed');
  542. $wrap.removeClass('validation-failed');
  543. } else {
  544. jElm.addClass('validation-passed');
  545. jElm.removeClass('validation-failed');
  546. }
  547. },
  548. newErrorMsgAdvice : function(name,elm,errorMsg) {
  549. if(name.indexOf(".")!=-1){
  550. name = name.split(".")[1];
  551. }
  552. var advice = '<div class="validation-advice" id="advice-' + name + '-' + jValidation.util.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>';
  553. switch (elm.type && elm.type.toLowerCase()) {
  554. case 'checkbox':
  555. case 'radio':
  556. $(elm).after(advice);
  557. break;
  558. default:
  559. $(elm).after(advice);
  560. }
  561. advice = $('#advice-' + name + '-' + jValidation.util.getElmID(elm));
  562. return advice;
  563. },
  564. newSuccessMsgAdvice : function(name,elm) {
  565. var advice = '<span class="validation-success-advice glyphicon glyphicon-ok crm-success-color" id="advice-' + name + '-' + jValidation.util.getElmID(elm) +'"></span>';
  566. switch (elm.type && elm.type.toLowerCase()) {
  567. case 'checkbox':
  568. case 'radio':
  569. var p = elm.parentNode;
  570. if(p) {
  571. $(elm).before(advice);
  572. } else {
  573. $(elm).after(advice);
  574. }
  575. break;
  576. case 'input':
  577. $(elm).after(advice);
  578. default:
  579. $(elm).after(advice);
  580. }
  581. advice = $('#advice-' + name + '-' + jValidation.util.getElmID(elm));
  582. return advice;
  583. },
  584. hideErrorMsg : function(name,elm) {
  585. var prop = jValidation.Validation._getAdviceProp(name);
  586. var advice = jValidation.Validation.getAdvice(name, elm);
  587. var jElm = $(elm);
  588. if(advice && jElm.attr(prop)) {
  589. advice.hide();
  590. }
  591. jElm.attr(prop,false);
  592. //jElm.removeClass('validation-failed');
  593. //jElm.addClass('validation-passed');
  594. var $wrap = jElm.closest('.j-text-wrapper');
  595. if($wrap.length) {
  596. $wrap.addClass('validation-passed');
  597. $wrap.removeClass('validation-failed');
  598. } else {
  599. jElm.addClass('validation-passed');
  600. jElm.removeClass('validation-failed');
  601. }
  602. },
  603. reset : function(elm) {
  604. var jElm = $(elm);
  605. if(jValidation.Tips.useTips){
  606. if($(elm).data("jtip")){
  607. $(elm).unbind("mouseover");
  608. $(elm).data("jtip").tipWrap.remove();
  609. $(elm).parent().find(".validation-success-advice").remove();
  610. }
  611. }else{
  612. var className = jElm.attr("class");
  613. var cn = className.split(/\s+/);
  614. for(var i = 0; i < cn.length; i++) {
  615. var value = cn[i];
  616. var prop = jValidation.Validation._getAdviceProp(value);
  617. if(jElm.attr(prop)) {
  618. var advice = jValidation.Validation.getAdvice(value, elm);
  619. advice.hide();
  620. jElm.attr(prop,'');
  621. }
  622. }
  623. }
  624. var $wrap = jElm.closest('.j-text-wrapper');
  625. if($wrap.length) {
  626. $wrap.removeClass('validation-passed');
  627. $wrap.removeClass('validation-failed');
  628. } else {
  629. jElm.removeClass('validation-passed');
  630. jElm.removeClass('validation-failed');
  631. }
  632. },
  633. resetCheckbox:function(elm){
  634. this.reset(elm);
  635. $("#check-advice-" + jValidation.util.getElmID(elm)).remove();
  636. if(elm.type && (elm.type.toLowerCase() == 'radio' || elm.type.toLowerCase() == 'checkbox')){
  637. if($(elm).parent().hasClass("validation-failed-span")){
  638. $(elm).unwrap();
  639. }
  640. }
  641. },
  642. _getAdviceProp : function(validatorName) {
  643. return '__advice'+validatorName;
  644. },
  645. getAdvice : function(name, elm) {
  646. //judge is exist a custom advice
  647. var advice = $('#advice-'+name+'-'+jValidation.util.getElmID(elm));
  648. if(advice.size()>0){
  649. return advice;
  650. }else{
  651. return $('#advice-'+jValidation.util.getElmID(elm));
  652. }
  653. },
  654. get : function(cssName) {
  655. var Validation = jValidation.Validation;
  656. var resultMethodName = null;
  657. for(var methodName in Validation.methods) {
  658. if(cssName == methodName) {
  659. resultMethodName = methodName;
  660. break;
  661. }
  662. if(cssName.indexOf(methodName) >= 0) {
  663. resultMethodName = methodName;
  664. }
  665. }
  666. return Validation.methods[resultMethodName] ? Validation.methods[resultMethodName] : new jValidation.Validator();
  667. },
  668. add : function(className, test, options) {
  669. var nv = {};
  670. var testFun = test;
  671. if(test instanceof RegExp){
  672. testFun = function(v,elm,args,metadata){ return test.test(v);};
  673. }
  674. nv[className] = new jValidation.Validator(className, testFun, options);
  675. $.extend(true,jValidation.Validation.methods,nv);
  676. },
  677. addAllThese : function(validators) {
  678. for(var i = 0; i < validators.length; i++) {
  679. var value = validators[i];
  680. jValidation.Validation.add(value[0], value[1], (value.length > 2 ? value[2] : {}));
  681. }
  682. },
  683. methods : {},
  684. validations : {}
  685. });
  686. $.extend({ jValidation: jValidation });
  687. })(jQuery);
  688. /**
  689. * init Validation validation methods
  690. */
  691. (function(Validation, $){
  692. /**
  693. * Define global and singleton object jValidation
  694. */
  695. var jValidation = $.jValidation || {};
  696. var Tips = $.Tips || {};
  697. var Util = $.Util;
  698. Validation.addAllThese([
  699. ['required', function(v, elm) {
  700. var type = $(elm).attr("data-type");
  701. if(type && Util.isStrEqualsIgnorecase(type, "comboSelect")) {
  702. if(Util.isString(v)) {
  703. var data = JSON.parse(v);
  704. if(!data.keys || !data.keys.length || !data.keys.join()) {
  705. return false;
  706. } else {
  707. return true;
  708. }
  709. }
  710. }
  711. return !((v == null) || (v.length == 0) || /^[\s|\u3000]+$/.test(v));
  712. },{ignoreEmptyValue:false}],
  713. ['invalidchar', function(v) {
  714. return (/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(v));
  715. }],
  716. ['validate-number', function(v) {
  717. return (!isNaN(v) && !/^\s+$/.test(v));
  718. }],
  719. ['validate-digits', function(v) {
  720. return !/[^\d]/.test(v);
  721. }],
  722. ['validate-alphanum', function(v) {
  723. return !/\W/.test(v);
  724. }],
  725. ['validate-one-required', function (v,elm) {
  726. var p = elm.parentNode;
  727. var size = $(elm).parent().find("input[type='radio']:checked").size();
  728. return size !=0;
  729. },{ignoreEmptyValue : false}],
  730. ['validate-digits',/^[\d]+$/],
  731. ['validate-positive-integer',/^[1-9]([0-9])*$/],
  732. ['validate-alphanum',/^[a-zA-Z0-9]+$/],
  733. ['validate-alpha',/^[a-zA-Z]+$/],
  734. ['validate-email',/\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/],
  735. ['validate-url',/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i],
  736. ['validate-currency-dollar',/^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/]
  737. ]);
  738. //custom validate start
  739. Validation.addAllThese([
  740. /**
  741. * Usage : equals-$otherInputId
  742. * Example : equals-username or equals-email etc..
  743. */
  744. ['equals', function(v,elm,args,metadata) {
  745. return $("#"+args[0]).val() == v;
  746. },{ignoreEmptyValue:false}],
  747. ['equals-ignore-case', function(v,elm,args,metadata) {
  748. return Util.isStrEqualsIgnorecase( $("#"+args[0]).val(), v);
  749. },{ignoreEmptyValue:false}],
  750. /**
  751. * Usage : less-than-$otherInputId
  752. */
  753. ['less-than', function(v,elm,args,metadata) {
  754. if(Validation.get('validate-number').test(v) && Validation.get('validate-number').test($("#"+args[0])))
  755. return parseFloat(v) < parseFloat($("#"+args[0]));
  756. return v < $("#"+args[0]);
  757. }],
  758. /**
  759. * Usage : less-than-equal-$otherInputId
  760. */
  761. ['less-than-equal', function(v,elm,args,metadata) {
  762. var val = $("#"+args[0]);
  763. if(Validation.get('validate-number').test(v) && Validation.get('validate-number').test(val))
  764. return parseFloat(v) <= parseFloat(val);
  765. return v < val || v == val;
  766. }],
  767. /**
  768. * Usage : great-than-$otherInputId
  769. */
  770. ['great-than', function(v,elm,args,metadata) {
  771. if(Validation.get('validate-number').test(v) && Validation.get('validate-number').test($("#"+args[0])))
  772. return parseFloat(v) > parseFloat($("#"+args[0]));
  773. return v > $("#"+args[0]);
  774. }],
  775. /**
  776. * Usage : great-than-equal-$otherInputId
  777. */
  778. ['great-than-equal', function(v,elm,args,metadata) {
  779. var val = $("#"+args[0]);
  780. if(Validation.get('validate-number').test(v) && Validation.get('validate-number').test(val))
  781. return parseFloat(v) >= parseFloat(val);
  782. return v > val || v == val;
  783. }],
  784. /*
  785. * Usage: min-length-$number
  786. * Example: min-length-10
  787. */
  788. ['min-length',function(v,elm,args,metadata) {
  789. return v.length >= parseInt(args[0]);
  790. }],
  791. /*
  792. * Usage: max-length-$number
  793. * Example: max-length-10
  794. */
  795. ['max-length',function(v,elm,args,metadata) {
  796. return v.length <= parseInt(args[0]);
  797. }],
  798. /*
  799. * Usage: validate-file-$type1-$type2-$typeX
  800. * Example: validate-file-png-jpg-jpeg
  801. */
  802. ['validate-file',function(v,elm,args,metadata) {
  803. return $("#"+args).any(function(extentionName) {
  804. return new RegExp('\\.'+extentionName+'$','i').test(v);
  805. });
  806. }],
  807. /*
  808. * Usage: float-range-$minValue-$maxValue
  809. * Example: -2.1 to 3 = float-range--2.1-3
  810. */
  811. ['float-range',function(v,elm,args,metadata) {
  812. return (parseFloat(v) >= parseFloat(args[0]) && parseFloat(v) <= parseFloat(args[1]));
  813. },{depends : ['validate-number']}],
  814. /*
  815. * Usage: int-range-$minValue-$maxValue
  816. * Example: -10 to 20 = int-range--10-20
  817. */
  818. ['int-range',function(v,elm,args,metadata) {
  819. return (parseInt(v) >= parseInt(args[0]) && parseInt(v) <= parseInt(args[1]));
  820. },{depends : ['validate-integer']}],
  821. /*
  822. * Usage: length-range-$minLength-$maxLength
  823. * Example: 10 to 20 = length-range-10-20
  824. */
  825. ['length-range',function(v,elm,args,metadata) {
  826. return (v.length >= parseInt(args[0]) && v.length <= parseInt(args[1]));
  827. }],
  828. /*
  829. * Usage: max-value-$number
  830. * Example: max-value-10
  831. */
  832. ['max-value',function(v,elm,args,metadata) {
  833. return parseFloat(v) <= parseFloat(args[0]);
  834. },{depends : ['validate-number']}],
  835. /*
  836. * Usage: min-value-$number
  837. * Example: min-value-10
  838. */
  839. ['min-value',function(v,elm,args,metadata) {
  840. return parseFloat(v) >= parseFloat(args[0]);
  841. },{depends : ['validate-number']}],
  842. /*
  843. * Usage: validate-pattern-$RegExp
  844. * Example: <input id='sex' class='validate-pattern-/^[fm]$/i'>
  845. */
  846. ['validate-pattern',function(v,elm,args,metadata) {
  847. return eval('('+args.singleArgument+'.test(v))');
  848. }],
  849. /*
  850. * Usage: validate-ajax-$url
  851. * Example: <input id='email' class='validate-ajax-http://localhost:8080/validate-email.jsp'>
  852. */
  853. ['validate-ajax',function(v,elm,args,metadata) {
  854. //TODO has been abolished
  855. return true;
  856. },{ignoreEmptyValue:false}],
  857. /*
  858. * Usage: validate-dwr-${service}.${method}
  859. * Example: <input id='email' class='validate-dwr-service.method'>
  860. */
  861. ['validate-dwr',function(v,elm,args,metadata) {
  862. var result = false;
  863. var callback = function(methodResult) {
  864. if(methodResult)
  865. metadata._error = methodResult;
  866. else
  867. result = true;
  868. };
  869. var call = args.singleArgument+"('"+v+"',callback)";
  870. DWREngine.setAsync(false);
  871. eval(call);
  872. DWREngine.setAsync(true);
  873. return result;
  874. }],
  875. /*
  876. * Usage: validate-buffalo-${service}.${method}
  877. * Example: <input id='email' class='validate-buffalo-service.method'>
  878. */
  879. ['validate-buffalo',function(v,elm,args,metadata) {
  880. var result = false;
  881. var callback = function(reply) {
  882. if(replay.getResult())
  883. metadata._error = replay.getResult();
  884. else
  885. result = true;
  886. };
  887. if(!BUFFALO_END_POINT) alert('not found "BUFFALO_END_POINT" variable');
  888. var buffalo = new Buffalo(BUFFALO_END_POINT,false);
  889. buffalo.remoteCall(args.singleArgument,v,callback);
  890. return result;
  891. }],
  892. /*
  893. * Usage: validate-date-$dateFormat or validate-date($dateFormat default is yyyy-MM-dd)
  894. * Example: validate-date-yyyy/MM/dd
  895. */
  896. ['validate-date', function(v,elm,args,metadata) {
  897. var dateFormat = args.singleArgument || 'yyyy-MM-dd';
  898. metadata._error = jValidation.util.format(jValidation.util.getI18nMsg(metadata.className),[dateFormat,dateFormat.replace('yyyy','2006').replace('MM','03').replace('dd','12')]);
  899. return jValidation.util.isDate(v,dateFormat,elm,"1");
  900. }],
  901. ['validate-selection', function(v,elm,args,metadata) {
  902. return elm.options ? elm.selectedIndex > 0 : !((v == null) || (v.length == 0));
  903. }],
  904. /**
  905. *
  906. *Example :checkbox-required-2
  907. */
  908. ['checkbox-required', function(v,elm,args,metadata) {
  909. var size = 0;
  910. var $wrap = $(elm).closest('.j-checkbox-wrapper');
  911. if($wrap.length) {
  912. size = $wrap.find("input[type='checkbox']:checked").size();
  913. } else {
  914. size = $(elm).parent().find("input[type='checkbox']:checked").size();
  915. }
  916. return size !=0;
  917. },{ignoreEmptyValue:false}],
  918. ['validate-integer',/^[-+]?[1-9]\d*$|^0$/],
  919. ['validate-ip',/^(?:(?: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]?)$/],
  920. //中国相关验证开始
  921. ['validate-id-number',function(v,elm,args,metadata) {
  922. if(!(/^\d{17}(\d|x)$/i.test(v) || /^\d{15}$/i.test(v))) return false;
  923. var provinceCode = parseInt(v.substr(0,2));
  924. if((provinceCode < 11) || (provinceCode > 91)) return false;
  925. var forTestDate = v.length == 18 ? v : v.substr(0,6)+"19"+v.substr(6,15);
  926. var birthday = forTestDate.substr(6,8);
  927. //TODO CYC 20160418
  928. //if(!jValidation.util.isDate(birthday,'yyyyMMdd')) return false;
  929. if(!jValidation.util.isDate(birthday,'yyyyMMdd')) return false;
  930. if(v.length == 18) {
  931. v = v.replace(/x$/i,"a");
  932. var verifyCode = 0;
  933. for(var i = 17;i >= 0;i--)
  934. verifyCode += (Math.pow(2,i) % 11) * parseInt(v.charAt(17 - i),11);
  935. if(verifyCode % 11 != 1) return false;
  936. }
  937. return true;
  938. }],
  939. ['validate-chinese',/^[\u4e00-\u9fa5]+$/],
  940. ['validate-phone',/^((0[1-9]{3})?(0[12][0-9])?[-])?\d{6,8}$/],
  941. ['validate-mobile-phone',/^0?(13[0-9]|15[0-9]|18[0-9]|14[57]|17[0-9])[0-9]{8}$/],
  942. ['validate-mobile-and-phone', function (v,elm,args,metadata) {
  943. if(/^((0[1-9]{3})?(0[12][0-9])?[-]?)?\d{6,8}$/.test(v) || /^0?(13[0-9]|15[0-9]|18[0-9]|14[57]|17[0-9])[0-9]{8}$/.test(v))
  944. return true;
  945. return false
  946. }],
  947. ['validate-zip',/^[1-9]\d{5}$/],
  948. ['validate-qq',/^[1-9]\d{4,8}$/],
  949. ['validate-devid',/^[0-9A-Z]{6}$/],
  950. ['validate-space',/^[^\s]+$/],
  951. ['validate-money',/^[0-9]+([.]{1}[0-9]{1,2})?$/],
  952. ['validate-contact-way',/^((0[1-9]{3})?(0[12][0-9])?[-])?\d{6,8}|0?(13[0-9]|15[012356789]|18[012356789]|14[57])[0-9]{8}$/],
  953. ['validate-org-length', function (v,elm,args,metadata) {
  954. v = eval("("+v+")");
  955. var len;
  956. if (Util.isStrEquals(elm.id,"location"))
  957. len = 1;
  958. else
  959. len = 2;
  960. if(v.keys[0]!="" && (v.keys.length<3 || v.keys[len]==""))
  961. return false;
  962. return true;
  963. }],
  964. ['validate-org-code', /^[0-9A-Z]{8}[-][0-9A-Z]{1}$/],
  965. ['validate-special-char', function (v,elm,args,metadata) {
  966. var pattern = new RegExp("[']");
  967. if (pattern.test(v))
  968. return false;
  969. return true;
  970. }]
  971. ]);
  972. })(jQuery.jValidation.Validation,jQuery);