How to use _item method in Cypress

Best JavaScript code snippet using cypress

Valid.js

Source:Valid.js Github

copy

Full Screen

1//TODO: 错误提示 不占用页面宽高, 使用 position = absolute, date = 2013-08-032//TODO: checkbox, radio 错误时, input 添加高亮显示3//TODO: daterange 支持一对多关系4//TODO: datavalid 添加自定义 ajax 数据 和 方法 5;(function(define, _win) { 'use strict'; define( 'JC.Valid', [ 'JC.common' ], function(){6 /**7 * <b>表单验证</b> (单例模式)8 * <br />全局访问请使用 JC.Valid 或 Valid9 * <p><b>require</b>: 10 * <a href='JC.common.html'>JC.common</a>11 * </p>12 * <p><a href='https://github.com/openjavascript/jquerycomps' target='_blank'>JC Project Site</a>13 * | <a href='http://jc2.openjavascript.org/docs_api/classes/JC.Valid.html' target='_blank'>API docs</a>14 * | <a href='../../modules/JC.Valid/0.2/_demo/' target='_blank'>demo link</a></p>15 * <h2>Form 的可用 html attribute</h2>16 * <dl>17 * <dt>errorabort = bool, default = true</dt>18 * <dd>19 * 查检Form Control时, 如果发生错误是否继续检查下一个20 * <br />true: 继续检查, false, 停止检查下一个21 * </dd>22 *23 * <dt>validmsg = bool | string</dt>24 * <dd>25 * 内容填写正确时显示的 提示信息, class=validmsg26 * <br />如果 = 0, false, 将不显示提示信息27 * <br />如果 = 1, true, 将不显示提示文本28 * </dd>29 *30 * <dt>validemdisplaytype = string, default = inline</dt>31 * <dd>32 * 设置 表单所有控件的 em CSS display 显示类型33 * </dd>34 *35 * <dt>ignoreAutoCheckEvent = bool, default = false</dt>36 * <dd>是否禁用 自动 check 事件( focus, blur, change )</dd>37 * </dl>38 * <h2>Form Control的可用 html attribute</h2>39 * <dl>40 * <dt>reqmsg = 错误提示</dt>41 * <dd>值不能为空, class=error errormsg</dd>42 *43 * <dt>errmsg = 错误提示</dt>44 * <dd>格式错误, 但不验证为空的值, class=error errormsg</dd>45 *46 * <dt>focusmsg = 控件获得焦点的提示信息</dt>47 * <dd>48 * 这个只作提示用, class=focusmsg49 * </dd>50 *51 * <dt>validmsg = bool | string</dt>52 * <dd>53 * 内容填写正确时显示的 提示信息, class=validmsg54 * <br />如果 = 0, false, 将不显示提示信息55 * <br />如果 = 1, true, 将不显示提示文本56 * </dd>57 *58 * <dt>emel = selector</dt>59 * <dd>显示错误信息的selector</dd>60 *61 * <dt>validel = selector</dt>62 * <dd>显示正确信息的selector</dd>63 *64 * <dt>focusel = selector</dt>65 * <dd>显示提示信息的selector</dd>66 *67 * <dt>validemdisplaytype = string, default = inline</dt>68 * <dd>69 * 设置 em 的 CSS display 显示类型70 * </dd>71 *72 * <dt>ignoreprocess = bool, default = false</dt>73 * <dd>验证表单控件时, 是否忽略</dd>74 *75 * <dt>minlength = int(最小长度)</dt>76 * <dd>验证内容的最小长度, 但不验证为空的值</dd>77 *78 * <dt>maxlength = int(最大长度)</dt>79 * <dd>验证内容的最大长度, 但不验证为空的值</dd>80 *81 * <dt>minvalue = number|ISO date(最小值)</dt>82 * <dd>验证内容的最小值, 但不验证为空的值</dd>83 *84 * <dt>maxvalue = number|ISO date(最大值)</dt>85 * <dd>验证内容的最大值, 但不验证为空的值</dd>86 *87 * <dt>validitemcallback = function</dt>88 * <dd>89 * 对一个 control 作检查后的回调, 无论正确与否都会触发, <b>window 变量域</b>90<pre>function validItemCallback( &#95;selector, &#95;isValid ){91}</pre>92 * </dd>93 *94 * <dt>validHidden = bool, default = false</dt>95 * <dd>是否验证隐藏的控件</dd>96 *97 * <dt>rangeCanEqual = bool, default = true</dt>98 * <dd>nrange 和 daterange 的开始值和结束值是否可以相等</dd>99 *100 * <dt>datatype: 常用数据类型</dt>101 * <dd><b>n:</b> 检查是否为正确的数字</dd>102 * <dd><b>n-i.f:</b> 检查数字格式是否附件要求, i[整数位数], f[浮点数位数], n-7.2 = 0.00 ~ 9999999.99</dd>103 * <dd>104 * <b>nrange:</b> 检查两个control的数值范围105 * <dl>106 * <dd>html attr <b>fromNEl:</b> 指定开始的 control</dd>107 * <dd>html attr <b>toNEl:</b> 指定结束的 control</dd>108 * <dd>如果不指定 fromNEl, toNEl, 默认是从父节点下面找到 nrange, 按顺序定为 fromNEl, toNEl</dd>109 * </dl>110 * </dd>111 * <dd><b>f:</b> 检查是否为正确的数字, default: f-9.2</dd>112 * <dd><b>f-i.f:</b> 检查数字格式是否附件要求, i[整数位数], f[浮点数位数], f-7.2 = 0.00 ~ 9999999.99</dd>113 * <dd><b>d:</b> 检查是否为正确的日期, YYYYMMDD, YYYY/MM/DD, YYYY-MM-DD, YYYY.MM.DD</dd>114 * <dd>115 * <b>daterange:</b> 检查两个control的日期范围116 * <dl>117 * <dd>html attr <b>fromDateEl:</b> 指定开始的 control</dd>118 * <dd>html attr <b>toDateEl:</b> 指定结束的 control</dd>119 * <dd>如果不指定 fromDateEl, toDateEl, 默认是从父节点下面找到 daterange, 按顺序定为 fromDateEl, toDateEl</dd>120 * <dd>html attr <b>datespan:</b>, 指定开始与结束日期的时间跨度(JC.f.dateDetect)</dd>121 * </dl>122 * </dd>123 * <dd><b>time:</b> 是否为正确的时间, hh:mm:ss</dd>124 * <dd><b>minute:</b> 是否为正确的时间, hh:mm</dd>125 * <dd>126 * <b>bankcard:</b> 是否为正确的银行卡127 * <br />格式为: 9 ~ 25 位数字128 * </dd>129 * <dd>130 * <b>cnname:</b> 中文姓名131 * <br>格式: 汉字和大小写字母132 * <br>规则: 长度 2-32个字节, 非 ASCII 算2个字节133 * </dd>134 * <dd>135 * <b>enname:</b> 英文姓名136 * <br>格式: 大小写字母 + 空格137 * <br>规则: 长度 2-32个字节, 非 ASCII 算2个字节138 * </dd>139 * <dd>140 * <b>allname:</b> cnname | enname141 * <br />中文姓名和英文姓名的复合验证142 * </dd>143 * <dd>144 * <b>username:</b> 注册用户名145 * <br>格式: a-zA-Z0-9_-146 * <br>规则: 首字母必须为 [a-zA-Z0-9], 长度 2 - 30147 * </dd>148 * <dd><b>idnumber:</b> 身份证号码, 15~18 位</dd>149 * <dd><b>mobilecode:</b> 手机号码, 11位, (13|14|15|16|17|18|19)[\d]{9}</dd>150 * <dd><b>mobile:</b> mobilecode 的别名</dd>151 * <dd><b>mobilezonecode:</b> 带 国家代码的手机号码, [+国家代码] [零]11位数字</dd>152 * <dd><b>phonecode:</b> 电话号码, 7~8 位数字, [1-9][0-9]{6,7}</dd>153 * <dd><b>phone:</b> 带区号的电话号码, [区号][空格|空白|-]7~8位电话号码</dd>154 * <dd><b>phoneall:</b> 带国家代码, 区号, 分机号的电话号码, [+国家代码][区号][空格|空白|-]7~8位电话号码#1~6位</dd>155 * <dd><b>phonezone:</b> 电话区号, 3~4位数字. phonezone-n,m 可指定位数长度</dd>156 * <dd><b>phoneext:</b> 电话分机号, 1~6位数字</dd>157 * <dd><b>countrycode:</b> 地区代码, [+]1~6位数字</dd>158 * <dd><b>mobilephone:</b> mobilecode | phone</dd>159 * <dd><b>mobilephoneall:</b> mobilezonecode | phoneall</dd>160 * <dd><b>reg:</b> 自定义正则校验, /正则规则/[igm]</dd>161 * <dd>162 * <b>vcode:</b> 验证码, 0-9a-zA-Z, 长度 默认为4163 * <br />可通过 vcode-[\d], 指定验证码长度164 * </dd>165 * <dd>166 * <b>text:</b> 显示声明检查的内容为文本类型167 * <br />默认就是 text, 没有特殊原因其实不用显示声明168 * </dd>169 * <dd>170 * <b>bytetext:</b> 声明按字节检查文本长度171 * <br /> ASCII 算一个字符, 非 ASCII 算两个字符172 * </dd>173 * <dd><b>url:</b> URL 格式, ftp, http, https</dd>174 * <dd><b>domain:</b> 匹配域名, 宽松模式, 允许匹配 http(s), 且结尾允许匹配反斜扛(/)</dd>175 * <dd><b>stricdomain:</b> 匹配域名, 严格模式, 不允许匹配 http(s), 且结尾不允许匹配反斜扛(/)</dd>176 * <dd><b>email:</b> 电子邮件</dd>177 * <dd><b>zipcode:</b> 邮政编码, 0~6位数字</dd>178 * <dd><b>taxcode:</b> 纳税人识别号, 长度: 15, 18, 20 </dd>179 *180 * <dd>181 * <dl>182 * <dt>checkbox: 默认需要至少选中N 个 checkbox</dt>183 * <dd>184 * 默认必须选中一个 checkbox185 * <br > 如果需要选中N个, 用这种格式 checkbox-n, checkbox-3 = 必须选中三个186 * <br > datatarget: 声明所有 checkbox 的选择器187 * </dd>188 * </dl>189 * </dd>190 *191 * <dd>192 * <dl>193 * <dt>file: 判断文件扩展名</dt>194 * <dd>属性名(文件扩展名列表): fileext</dd>195 * <dd>格式: .ext[, .ext]</dd>196 * <dd>197<xmp> <input type="file" 198 reqmsg="文件" 199 errmsg="允许上传的文件类型: .gif, .jpg, .jpeg, .png"200 datatype="file" 201 fileext=".gif, .jpg, .jpeg, .png" 202 />203 <label>.gif, .jpg, .jpeg, .png</label>204 <em class="error"></em>205 <em class="validmsg"></em>206</xmp>207 </dd>208 * </dl>209 * </dd>210 *211 * <dd><b>qq:</b> 检查QQ号码, 5 ~ 11位数字</dd>212 * <dd><b>qqall:</b> 检查QQ号码, [ qq | email ]</dd>213 *214 * <dt>subdatatype: 特殊数据类型, 以逗号分隔多个属性</dt>215 * <dd>216 * <dl>217 * <dt>alternative: N 个 Control 必须至少有一个非空的值</dt>218 * <dd><b>datatarget:</b> 显式指定同一组 control, 默认在父级下查找[subdatatype=alternative]</dd>219 * <dd><b>alternativedatatarget:</b> 与 datatarget相同, 区别是优先级高于 datatarget</dd>220 * <dd><b>alternativemsg:</b> N 选一的错误提示</dd>221 *222 * <dd>223 * <b>alternativeReqTarget:</b> 为 alternative node 指定一个不能为空的 node224 * <br /><b>请使用 subdatatype = reqtarget</b>, 这个附加属性将弃除225 * </dd>226 * <dd><b>alternativeReqmsg:</b> alternativeReqTarget 目标 node 的html属性, 错误时显示的提示信息</dd>227 * </dl>228 * </dd>229 * <dd>230 * <dl>231 * <dt>reqtarget: 如果 selector 的值非空, 那么 datatarget 的值也不能为空</dt>232 * <dd><b>datatarget:</b> 显式指定 目标 target</dd>233 * <dd><b>reqTargetDatatarget:</b> 与 datatarget相同, 区别是优先级高于 datatarget</dd>234 * <dd><b>reqtargetmsg:</b> target node 用于显示错误提示的 html 属性</dd>235 * </dl>236 * </dd>237 * <dd>238 * <dl>239 * <dt>reconfirm: N 个 Control 的值必须保持一致</dt>240 * <dd><b>datatarget:</b> 显式指定同一组 control, 默认在父级下查找[subdatatype=reconfirm]</dd>241 * <dd><b>reconfirmdatatarget:</b> 与 datatarget相同, 区别是优先级高于 datatarget</dd>242 * <dd><b>reconfirmmsg:</b> 值不一致时的错误提示</dd>243 * </dl>244 * </dd>245 * <dd>246 * <dl>247 * <dt>unique: N 个 Control 的值必须保持唯一性, 不能有重复</dt>248 * <dd><b>datatarget:</b> 显式指定同一组 control, 默认在父级下查找[subdatatype=unique]</dd>249 * <dd><b>uniquedatatarget:</b> 与 datatarget相同, 区别是优先级高于 datatarget</dd>250 * <dd><b>uniquemsg:</b> 值有重复的提示信息</dd>251 * <dd><b>uniqueIgnoreCase:</b> 是否忽略大小写</dd>252 * <dd><b>uniqueIgnoreEmpty:</b> 是否忽略空的值, 如果组中有空值也会被忽略</dd>253 * <dd><b>processDisabled:</b> 是否处理 disabled 但 visible 的node</dd>254 * <dd>unique-n 可以指定 N 个为一组的匹配, unique-2 = 2个一组, unique-3: 三个一组</dd>255 * </dl>256 * </dd>257 * <dd>258 * <dl>259 * <dt>datavalid: 判断 control 的值是否合法( 通过HTTP请求验证 )</dt>260 * <dd><b>datavalidMsg:</b> 值不合法时的提示信息</dd>261 * <dd>262 * <b>datavalidUrl:</b> 验证内容正确与否的 url api263 * <p>{"errorno":0,"errmsg":""}</p>264 * errorno: 0( 正确 ), 非0( 错误 )265 * <p>datavalidurl="./data/handler.php?key={0}"</p>266 * {0} 代表 value267 * </dd>268 * <dd>269 * <b>datavalidCheckCallback:</b> 验证内容正确与否的回调(优先级比 datavalidUrl 高)270<pre>window.datavalidCheckCallback =271function (){272 var _r = { 'errorno': 1, errmsg:'验证码错误' }, _sp = $( this ), _v = _sp.val().trim().toLowerCase();273 if( _v && _v === window.CHECK_CODE ){274 _r.errorno = 0;275 }276 return _r;277};<pre>278 * </dd>279 * <dd><b>datavalidNoCache:</b> 是否禁止缓存, default = true</dd>280 * <dd><b>datavalidAjaxType:</b> ajax 请求类型, default = get</dd>281 * <dd><b>datavalidRequestData:</b> ajax 请求数据, json data</dd>282 * <dd>283 * <b>datavalidCallback:</b> 请求 datavalidUrl 后调用的回调284<pre>function datavalidCallback( _json ){285 var _selector = $(this);286});</pre>287 * </dd>288 * <dd>289 * <b>datavalidKeyupCallback:</b> 每次 keyup 的回调290<pre>function datavalidKeyupCallback( _evt ){291 var _selector = $(this);292});</pre>293 * </dd>294 * <dd>295 * <b>datavalidUrlFilter:</b> 请求数据前对 url 进行操作的回调296<pre>function datavalidUrlFilter( _url ){297 var _selector = $(this);298 _url = JC.f.addUrlParams( _url, { 'xtest': 'customData' } );299 return _url;300});</pre>301 * </dd>302 * </dl>303 * </dd>304 * <dd>305 * <dl>306 * <dt>hidden: 验证隐藏域的值</dt>307 * <dd>308 * 有些特殊情况需要验证隐藏域的值, 请使用 subdatatype="hidden"309 * </dd>310 * </dl>311 * </dd>312 *313 * <dd>314 * <dl>315 * <dt>ucheck: 用户自定义验证</dt>316 * <dd><b>ucheckmsg:</b> 验证出错的提示信息</dd>317 * <dd><b>ucheckCallback:</b> 用于验证的函数 <b>window变量域</b>318 *319<pre>function ucheck_n( _item ){320 var _r = false, _v = JC.f.parseFinance( _item.val() );321 if( _v === 0 || ( _v >= 30 && _v >= 50 ) ){322 _r = true;323 }324 return _r;325}</pre>326 * </dd>327 * </dl>328 * </dd>329 * <dd>330 * <dl>331 * <dt>subdatatype = even: 数值必须为偶数</dt>332 * </dl>333 * </dd>334 * <dd>335 * <dl>336 * <dt>subdatatype = odd: 数值必须为奇数</dt>337 * </dl>338 * </dd>339 * <dt>exdatatype: 特殊数据类型, 以逗号分隔多个属性, 该类型只用于显示视觉效果, 不作为实际验证的判断</dt>340 * <dd>341 * <dl>342 * <dt>datavalid: 判断 control 的值是否合法( 通过HTTP请求验证 )(只用于显示视觉效果, 不作为实际验证的判断)</dt>343 <dd>其他参数与 subdatatype = datavalid 相同</dd>344 </dl>345 </dd>346 * </dl>347 * @namespace JC348 * @class Valid349 * @static350 * @version 0.2, 2013-08-15(函数模式改单例模式)351 * @version 0.1, 2013-05-22352 * @author qiushaowei <suches@btbtd.org> | 75 team353 */354 window.JC = window.JC || {log:function(){}};355 JC.Valid = window.Valid = Valid;356 357 function Valid(){358 /**359 * 兼容函数式使用360 */361 var _args = JC.f.sliceArgs( arguments );362 if( _args.length ){363 return Valid.check.apply( null, _args );364 }365 if( Valid._instance ) return Valid._instance;366 Valid._instance = this;367 this._model = new Model();368 this._view = new View( this._model );369 this._init();370 }371 372 Valid.prototype = {373 _init:374 function(){375 var _p = this;376 $( [ this._view, this._model ] ).on(Model.BIND, function( _evt, _evtName, _cb ){377 _p.on( _evtName, _cb );378 });379 $([ this._view, this._model ] ).on(Model.TRIGGER, function( _evt, _evtName ){380 var _data = JC.f.sliceArgs( arguments ).slice(2);381 _p.trigger( _evtName, _data );382 });383 _p.on( Model.CORRECT, function( _evt ){384 var _data = JC.f.sliceArgs( arguments ).slice(1);385 _p._view.valid.apply( _p._view, _data );386 });387 _p.on( Model.ERROR, function( _evt ){388 var _data = JC.f.sliceArgs( arguments ).slice(1);389 _p._view.error.apply( _p._view, _data );390 });391 _p.on( Model.FOCUS_MSG, function( _evt ){392 var _data = JC.f.sliceArgs( arguments ).slice(1);393 _p._view.focusmsg.apply( _p._view, _data );394 });395 this._view.init();396 return this;397 } 398 /**399 * 使用 jquery on 绑定事件400 * @method {string} on401 * @param {string} _evtName402 * @param {function} _cb403 * @return ValidInstance404 * @private405 */406 , on: function( _evtName, _cb ){ $(this).on(_evtName, _cb ); return this;}407 /**408 * 使用 jquery trigger 绑定事件409 * @method {string} trigger410 * @param {string} _evtName411 * @return ValidInstance412 * @private413 */414 , trigger: function( _evtName, _data ){ $(this).trigger( _evtName, _data ); return this;}415 /**416 * 分析_item是否附合规则要求417 * @method parse418 * @param {selector} _item 419 * @private420 */421 , parse: 422 function( _item ){423 var _p = this, _r = true, _item = $( _item );424 if( _item.prop( 'nodeName' ).toLowerCase() == 'object' ) return _r;425 if( !_p._model.isAvalible( _item ) ) return _r;426 if( !_p._model.isValid( _item ) ) return _r;427 if( Valid.ignore( _item ) ) return _r;428 var _dt = _p._model.parseDatatype( _item )429 , _nm = _item.prop('nodeName').toLowerCase();430 switch( _nm ){431 case 'input':432 case 'textarea':433 {434 ( _item.attr('type') || '' ).toLowerCase() != 'file' 435 && _p._model.isAutoTrim( _item ) 436 && _item.val( $.trim( _item.val() ) );437 break;438 }439 }440 if( !_p._model.reqmsg( _item ) ){ 441 _item.attr( 'datatypestatus', 'false' );442 return _r = false; 443 }444 if( !_p._model.lengthValid( _item ) ){ 445 _item.attr( 'datatypestatus', 'false' );446 return _r = false; 447 }448 //验证 datatype449 if( _dt && _p._model[ _dt ] && _item.val() ){450 if( !_p._model[ _dt ]( _item ) ){ 451 _item.attr( 'datatypestatus', 'false' );452 return _r = false; 453 }454 }455 _item.attr( 'datatypestatus', 'true' );456 //验证子类型457 var _subDtLs = _item.attr('subdatatype');458 if( _subDtLs ){459 _subDtLs = _subDtLs.replace(/[\s]+/g, '').split( /[,\|]/);460 $.each( _subDtLs, function( _ix, _sdt ){461 _sdt = _p._model.parseSubdatatype( _sdt );462 if( _sdt && _p._model[ _sdt ] && ( _item.val() || _sdt == 'alternative' ) ){463 if( !_p._model[ _sdt ]( _item ) ){ 464 _r = false; 465 return false;466 }467 }468 });469 }470 _r && _p.trigger( Model.CORRECT, _item ); 471 return _r;472 }473 , check:474 function(){475 var _p = this, _r = true, _items = JC.f.sliceArgs( arguments ), i, j;476 $.each( _items, function( _ix, _item ){477 _item = $(_item);478 Valid.isFormValid = false;479 if( _p._model.isForm( _item ) ){480 Valid.isFormValid = true;481 var _errorabort = _p._model.isErrorAbort( _item )482 , _isIgnoreForm = Valid.ignore( _item )483 , tmp484 ;485 for( i = 0, j = _item[0].length; i < j; i++ ){486 var _sitem = $(_item[0][i]);487 if( _isIgnoreForm && ! ( _sitem.val() || '' ).trim() ) continue;488 !_p.parse( _sitem ) && ( _r = false );489 if( _errorabort && !_r ) break;490 }491 }492 else if( Valid.isFormControl( _item ) ) {493 !_p.parse( _item ) && ( _r = false );494 }495 else{496 !_p.check( _item.find( Valid._formControls ) ) && ( _r = false );497 }498 });499 return _r;500 }501 , clearError:502 function(){503 var _items = JC.f.sliceArgs( arguments ), _p = this;504 $.each( _items, function( _ix, _item ){505 $( _item ).each( function(){506 var _item = $(this);507 switch( _item.prop('nodeName').toLowerCase() ){508 case 'form': 509 {510 for( var i = 0, j = _item[0].length; i < j; i++ ){511 Valid.setValid( $(_item[0][i]), 1, true );512 }513 break;514 }515 default: Valid.setValid( _item, 1, true ); break;516 }517 });518 });519 return this;520 }521 , isValid: function( _selector ){ return this._model.isValid( _selector ); }522 }523 /**524 * 验证一个表单项, 如 文本框, 下拉框, 复选框, 单选框, 文本域, 隐藏域525 * @method check526 * @static527 * @param {selector} _item 需要验证规则正确与否的表单/表单项( <b>可同时传递多个_item</b> )528 * @example 529 * JC.Valid.check( $( selector ) );530 * JC.Valid.check( $( selector ), $( anotherSelector );531 * JC.Valid.check( document.getElementById( item ) );532 *533 * if( !JC.Valid.check( $('form') ) ){534 * _evt.preventDefault();535 * return false;536 * }537 * @return {boolean}538 */539 Valid.checkAll = Valid.check = 540 function(){ return Valid.getInstance().check.apply( Valid.getInstance(), JC.f.sliceArgs( arguments ) ); }541 /**542 * 这个方法是 <a href='JC.Valid.html#method_check'>Valid.check</a> 的别名543 * @method checkAll544 * @static545 * @param {selector} _item - 需要验证规则正确与否的表单/表单项546 * @see Valid.check547 */548 /**549 * 获取 Valid 的实例 ( <b>Valid 是单例模式</b> )550 * @method getInstance551 * @param {selector} _selector552 * @static553 * @return {Valid instance}554 */555 Valid.getInstance = function(){ !Valid._instance && new Valid(); return Valid._instance; };556 /**557 * 检查是否需要延时 check558 * <br />以 html 属性 validCheckTimeout 定义, int 类型, type = ms559 * @method checkTimeout560 * @param {selector} _selector561 * @param {int} _tm562 * @static563 * @return {Valid instance}564 */565 Valid.checkTimeout =566 function( _selector, _tm ){567 _selector && ( _selector = $( _selector ) );568 if( !( _selector && _selector.length ) ) return;569 _tm = parseInt( _selector.attr( 'validCheckTimeout') ) || _tm;570 var _dname = 'VALID_CHECK_TIMEOUT';571 if( _tm ){572 _selector.data( _dname ) && clearTimeout( _selector.data( _dname ) );573 _selector.data( _dname , setTimeout( function(){574 Valid.check( _selector );575 }, _tm ));576 }else{577 Valid.check( _selector );578 }579 };580 /**581 * 判断/设置 selector 的数据是否合法582 * <br /> 通过 datavalid 属性判断583 * @method dataValid584 * @param {selector} _selector585 * @param {bool} _settter586 * @param {bool} _noStatus587 * @param {string} _customMsg588 * @static589 * @return bool590 */591 Valid.dataValid =592 function( _selector, _settter, _noStatus, _customMsg ){593 var _r = false, _msg = 'datavalidmsg';594 _selector && ( _selector = $( _selector ) );595 if( typeof _settter != 'undefined' ){596 _r = _settter;597 _selector.attr( 'datavalid', _settter );598 if( !_noStatus ){599 if( _settter ){600 //Valid.setValid( _selector );601 _selector.trigger('blur', [true]);602 }else{603 _customMsg && ( _msg = ' ' + _customMsg );604 Valid.setError( _selector, _msg, true );605 }606 }607 }else{608 if( _selector && _selector.length ){609 _r = JC.f.parseBool( _selector.attr('datavalid') );610 }611 }612 return _r;613 };614 /**615 * 判断 selector 是否 Valid 的处理对象616 * @method isValid617 * @param {selector} _selector618 * @return bool619 * @static620 */621 Valid.isValid = function( _selector ){ return Valid.getInstance().isValid( _selector ); };622 /**623 * 提供对各种显示状态 setTimeout 执行的正确性 控制逻辑624 */625 Valid.statusTimeout = {626 valid:627 function( _selector, _tm ){628 _selector && ( _selector = $( _selector ) );629 if( !( _selector && _selector.length ) ) return;630 _selector.data( Model.TIMEOUT_VALID ) && clearTimeout( _selector.data( Model.TIMEOUT_VALID ) );631 _tm && Valid.statusTimeout.clear();632 _tm && _selector.data( Model.TIMEOUT_VALID, _tm );633 }634 , error:635 function( _selector, _tm ){636 _selector && ( _selector = $( _selector ) );637 if( !( _selector && _selector.length ) ) return;638 _selector.data( Model.TIMEOUT_ERROR ) && clearTimeout( _selector.data( Model.TIMEOUT_ERROR ) );639 _tm && Valid.statusTimeout.clear();640 _tm && _selector.data( Model.TIMEOUT_ERROR, _tm );641 }642 , focus:643 function( _selector, _tm ){644 _selector && ( _selector = $( _selector ) );645 if( !( _selector && _selector.length ) ) return;646 _selector.data( Model.TIMEOUT_FOCUS ) && clearTimeout( _selector.data( Model.TIMEOUT_FOCUS ) );647 _tm && Valid.statusTimeout.clear();648 _tm && _selector.data( Model.TIMEOUT_FOCUS, _tm );649 }650 , success:651 function( _selector, _tm ){652 _selector && ( _selector = $( _selector ) );653 if( !( _selector && _selector.length ) ) return;654 _selector.data( Model.TIMEOUT_SUCCESS ) && clearTimeout( _selector.data( Model.TIMEOUT_SUCCESS ) );655 _tm && Valid.statusTimeout.clear();656 _tm && _selector.data( Model.TIMEOUT_SUCCESS, _tm );657 }658 , clear:659 function( _selector ){660 for( var k in Valid.statusTimeout ){661 if( k == 'clear' ) continue;662 Valid.statusTimeout[ k ]( _selector );663 }664 }665 };666 /**667 * 把一个表单项的状态设为正确状态668 * @method setValid669 * @param {selector} _items670 * @param {int} _tm 延时 _tm 毫秒显示处理结果, 默认=150671 * @static672 */673 Valid.setValid = function(_items, _tm, _noStyle, _isUserSet){ 674 _items = $( _items );675 _items.each( function( _ix, _item ){676 _item = $(this);677 Valid.statusTimeout.clear( _item );678 $( Valid.getInstance()._view ).trigger( 'setValid', [_item, _tm, _noStyle, _isUserSet] ); 679 });680 return Valid.getInstance();681 };682 /**683 * 把一个表单项的状态设为错误状态684 * @method setError685 * @param {selector} _items686 * @param {string} _msgAttr - 显示指定需要读取的错误信息属性名, 默认为 reqmsg, errmsg, 通过该属性可以指定别的属性名687 * <br /> 如果 _msgAttr 的第一个字符为空格, 将视为提示信息, 并自动生成属性 autoGenerateErrorMsg688 * @param {bool} _fullMsg - 显示指定错误信息为属性的值, 而不是自动添加的 请上传/选择/填写689 * @static690 */691 Valid.setError = 692 function(_items, _msgAttr, _fullMsg){ 693 _items = $(_items);694 _items.each( function( _ix, _item ){695 _item = $(this);696 Valid.statusTimeout.clear( _item );697 if( _msgAttr && _msgAttr.trim() && /^[\s]/.test( _msgAttr ) ){698 var _autoKey = 'autoGenerateErrorMsg';699 _item.attr( _autoKey, _msgAttr );700 _msgAttr = _autoKey;701 }702 $( Valid.getInstance()._view ).trigger( 'setError', [ _item, _msgAttr, _fullMsg ] );703 });704 return Valid.getInstance();705 };706 /**707 * 显示 focusmsg 属性的提示信息( 如果有的话 )708 * @method setFocusMsg709 * @param {selector} _items710 * @param {bool} _setHide711 * @param {string} _msgAttr - 显示指定需要读取的focusmsg信息属性名, 默认为 focusmsg, 通过该属性可以指定别的属性名712 * <br /> 如果 _msgAttr 的第一个字符为空格, 将视为提示信息, 并自动生成属性 autoGenerateFocusMsg713 * @static714 */715 Valid.focusmsg = Valid.setFocusMsg =716 function( _items, _setHide, _msgAttr ){ 717 _items = $( _items );718 _items.each( function( _ix, _item ){719 _item = $( this );720 Valid.statusTimeout.clear( _item );721 if( typeof _setHide == 'string' ){722 _msgAttr = _setHide;723 _setHide = false;724 }725 if( _msgAttr && _msgAttr.trim() && /^[\s]/.test( _msgAttr ) ){726 var _autoKey = 'autoGenerateFocusMsg';727 _item.attr( _autoKey, _msgAttr );728 _msgAttr = _autoKey;729 }730 Valid.getInstance().trigger( Model.FOCUS_MSG, [ _item, _setHide, _msgAttr ] ); 731 });732 return Valid.getInstance();733 };734 /**735 * focus 时,是否总是显示 focusmsg 提示信息736 * @property focusmsgEverytime737 * @type bool738 * @default true739 * @static740 */741 Valid.focusmsgEverytime = true;742 /**743 * 设置 em 的 css display 属性744 * @property emDisplayType745 * @type string746 * @default inline747 * @static748 */749 Valid.emDisplayType = 'inline';750 /**751 * 验证正确时, 是否显示正确的样式752 * @property showValidStatus753 * @type bool754 * @default false755 * @static756 */757 Valid.showValidStatus = false;758 /**759 * 清除Valid生成的错误样式760 * @method clearError761 * @static762 * @param {form|input|textarea|select|file|password} _selector - 需要清除错误的选择器763 * @example764 * JC.Valid.clearError( 'form' );765 * JC.Valid.clearError( 'input.some' );766 */767 Valid.clearError = 768 function(){ return Valid.getInstance().clearError.apply( Valid.getInstance(), JC.f.sliceArgs( arguments ) ); };769 /**770 * 验证发生错误时, 是否终止继续验证771 * <br /> 为真终止继续验证, 为假将验证表单的所有项, 默认为 false772 * @property errorAbort773 * @type bool774 * @default false775 * @static776 * @example777 $(document).ready( function($evt){778 JC.Valid.errorAbort = true;779 });780 */781 Valid.errorAbort = false;782 /**783 * 是否自动清除两边的空格784 * @property autoTrim785 * @type bool786 * @default true787 * @static788 * @example789 $(document).ready( function($evt){790 JC.Valid.autoTrim = false;791 });792 */793 Valid.autoTrim = true;794 /**795 * 对一个 control 作检查后的回调, 无论正确与否都会触发796 * @property itemCallback797 * @type function798 * @default undefined799 * @static800 * @example801 $(document).ready( function($evt){802 JC.Valid.itemCallback =803 function( _item, _isValid ){804 JC.log( 'JC.Valid.itemCallback _isValid:', _isValid );805 };806 });807 */808 Valid.itemCallback;809 /**810 * 判断 表单控件是否为忽略检查 或者 设置 表单控件是否为忽略检查811 * @method ignore812 * @param {selector} _item813 * @param {bool} _delIgnore 是否删除忽略属性, 如果为 undefined 将不执行 添加删除操作814 * @return bool815 * @static816 */817 Valid.ignore =818 function( _item, _delIgnore ){819 _item = $( _item );820 if( !( _item && _item.length ) ) return true;821 var _r = false;822 if( typeof _delIgnore != 'undefined' ){823 _delIgnore 824 ? _item.removeAttr('ignoreprocess')825 : _item.attr('ignoreprocess', true)826 ;827 _r = !_delIgnore;828 }else{829 830 _item.is( '[ignoreprocess]' ) 831 && (832 ( _item.attr('ignoreprocess') || '' ).trim()833 ? ( _r = JC.f.parseBool( _item.attr('ignoreprocess') ) )834 : ( _r = true )835 )836 ;837 }838 return _r;839 };840 /**841 * 定义 form control842 * @property _formControls843 * @param {selector} _selector844 * @return bool845 * @private846 * @static847 */848 Valid._formControls = 'input, select, textarea';849 /**850 * 判断 _selector 是否为 form control851 * @method isFormControl852 * @param {selector} _selector853 * @return bool854 * @static855 */856 Valid.isFormControl =857 function( _selector ){858 var _r = false;859 _selector 860 && ( _selector = $( _selector ) ).length861 && ( _r = _selector.is( Valid._formControls ) )862 ;863 return _r;864 };865 /**866 * 是否禁用 自动 check 事件( focus, blur, change )867 * @property ignoreAutoCheckEvent868 * @type bool869 * @default false870 * @static871 */872 Valid.ignoreAutoCheckEvent = false;873 874 function Model(){875 this._init();876 }877 Model.TRIGGER = 'TriggerEvent';878 Model.BIND = 'BindEvent';879 Model.ERROR = 'ValidError';880 Model.CORRECT = 'ValidCorrect';881 Model.FOCUS_MSG = 'ValidFocusMsg';882 Model.TIMEOUT_VALID = 'Valid_ValidTimeout';883 Model.TIMEOUT_ERROR = 'Valid_ErrorTimeout';884 Model.TIMEOUT_FOCUS = 'Valid_FocusTimeout';885 Model.TIMEOUT_SUCCESS = 'Valid_SuccessTimeout';886 Model.SELECTOR_ERROR = '~ em.error, ~ em.errormsg';887 Model.CSS_ERROR = 'error errormsg';888 Model.FILTER_ERROR = 'em.error em.errormsg';889 890 Model.prototype = {891 _init:892 function(){893 return this;894 }895 /**896 * 获取 _item 的检查类型897 * @static898 * @param {selector|string} _item899 */900 , parseDatatype: 901 function( _item ){902 var _r = ''903 if( typeof _item == 'string' ){904 _r = _item;905 }else{906 _r = _item.attr('datatype') || 'text';907 }908 return _r.toLowerCase().replace(/\-.*/, '');909 }910 /**911 * 获取 _item 的检查子类型, 所有可用的检查子类型位于 _logic.subdatatype 对象912 * @static913 * @param {selector|string} _item914 */915 , parseSubdatatype: 916 function( _item ){917 var _r = ''918 if( typeof _item == 'string' ){919 _r = _item;920 }else{921 _r = _item.attr('subdatatype') || '';922 }923 return _r.toLowerCase().replace(/\-.*/, '');924 }925 , isForm:926 function( _item ){927 var _r;928 _item.prop('nodeName') 929 && _item.prop('nodeName').toLowerCase() == 'form'930 && ( _r = true )931 ;932 return _r;933 }934 , isErrorAbort:935 function( _item ){936 var _r = Valid.errorAbort;937 _item.is('[errorabort]') && ( _r = JC.f.parseBool( _item.attr('errorabort') ) );938 return _r;939 }940 , isValid:941 function( _item ){942 _item = $(_item);943 var _r, _tmp;944 _item.each( function(){945 _tmp = $(this);946 if( _tmp.is( '[datatype]' ) || _tmp.is( '[subdatatype]' ) 947 || _tmp.is( '[minlength]' ) || _tmp.is( '[maxlength]' ) 948 || _tmp.is( '[reqmsg]' ) 949 || _tmp.is( 'form' ) 950 ) 951 _r = true;952 });953 return _r;954 }955 , isAutoTrim:956 function( _item ){957 _item = $( _item );958 /*959 //取form 的时候, 影响性能960 var _r = Valid.autoTrim, _form = $( _item.prop( 'form' ) );961 _form && _form.length && _form.is( '[validautotrim]' ) && ( _r = JC.f.parseBool( _form.attr('validautotrim') ) );962 _item.is( '[validautotrim]' ) && ( _r = JC.f.parseBool( _item.attr('validautotrim') ) );963 */964 var _r = Valid.autoTrim;965 _item.is( '[validautotrim]' ) && ( _r = JC.f.parseBool( _item.attr('validautotrim') ) );966 return _r;967 }968 , isReqmsg: function( _item ){ return _item.is('[reqmsg]'); }969 , isValidMsg: 970 function( _item ){ 971 _item = $( _item );972 var _r = Valid.showValidStatus, _form = JC.f.getJqParent( _item, 'form' );973 _form && _form.length && _form.is( '[validmsg]' ) && ( _r = JC.f.parseBool( _form.attr('validmsg') ) );974 _item.is( '[validmsg]' ) && ( _r = JC.f.parseBool( _item.attr('validmsg') ) );975 return _r;976 }977 , isAvalible: 978 function( _item ){979 return ( _item.is(':visible') || this.isValidHidden( _item ) ) && !_item.is('[disabled]');980 }981 , isValidHidden:982 function( _item ){983 var _r = false;984 _item.is( '[subdatatype]' )985 && /hidden/i.test( _item.attr( 'subdatatype' ) ) 986 && _item.parent().is( ':visible' )987 && ( _r = true )988 ;989 _item.is( '[validHidden]' ) 990 && ( _r = JC.f.parseBool( _item.attr( 'validHidden' ) || 'false' ) )991 ;992 return _r;993 }994 , validitemcallback: 995 function( _item ){ 996 _item = $( _item );997 var _r = Valid.itemCallback, _form = JC.f.getJqParent( _item, 'form' ), _tmp;998 _form &&_form.length 999 && _form.is( '[validitemcallback]' ) 1000 && ( _tmp = _form.attr('validitemcallback') )1001 && ( _tmp = window[ _tmp ] )1002 && ( _r = _tmp )1003 ;1004 _item.is( '[validitemcallback]' ) 1005 && ( _tmp = _item.attr('validitemcallback') )1006 && ( _tmp = window[ _tmp ] )1007 && ( _r = _tmp )1008 ;1009 return _r;1010 }1011 , isMinlength: function( _item ){ return _item.is('[minlength]'); }1012 , isMaxlength: function( _item ){ return _item.is('[maxlength]'); }1013 , minlength: function( _item ){ return parseInt( _item.attr('minlength'), 10 ) || 0; }1014 , maxlength: function( _item ){ return parseInt( _item.attr('maxlength'), 10 ) || 0; }1015 , isMinvalue: function( _item ){ return _item.is('[minvalue]'); }1016 , isMaxvalue: function( _item ){ return _item.is('[maxvalue]'); }1017 , isDatatarget: 1018 function( _item, _key ){ 1019 var _r = false, _defKey = 'datatarget';1020 _key 1021 && ( _key += _defKey )1022 && ( _r = _item.is( '[' + _key + ']' ) )1023 ;1024 !_r && ( _r = _item.is( '[' + _defKey + ']' ) );1025 return _r;1026 }1027 , datatarget: 1028 function( _item, _key ){ 1029 var _r, _defKey = 'datatarget';1030 _key 1031 && ( _key += _defKey )1032 && ( _key = _item.attr( _key ) )1033 && ( _r = JC.f.parentSelector( _item, _key ) )1034 ;1035 !( _r && _r.length ) && ( _r = JC.f.parentSelector( _item, _item.attr( _defKey ) ) );1036 return _r;1037 }1038 , minvalue: 1039 function( _item, _isFloat ){ 1040 if( typeof _isFloat == 'string' ){1041 var _datatype = _isFloat.toLowerCase().trim();1042 switch( _datatype ){1043 default:1044 {1045 return JC.f.parseDate( _item.attr('minvalue'), _item, true );1046 }1047 }1048 }else{1049 if( _isFloat ){1050 return parseFloat( _item.attr('minvalue') ) || 0; 1051 }else{1052 return parseInt( _item.attr('minvalue'), 10 ) || 0; 1053 }1054 }1055 }1056 , maxvalue: 1057 function( _item, _isFloat ){ 1058 if( typeof _isFloat == 'string' ){1059 var _datatype = _isFloat.toLowerCase().trim(), _r;1060 switch( _datatype ){1061 default:1062 {1063 return JC.f.parseDate( _item.attr('maxvalue'), _item, true );1064 }1065 }1066 }else{1067 if( _isFloat ){1068 return parseFloat( _item.attr('maxvalue') ) || 0; 1069 }else{1070 return parseInt( _item.attr('maxvalue'), 10 ) || 0; 1071 }1072 }1073 }1074 /**1075 * 检查内容的长度1076 * @static1077 * @param {selector} _item1078 * @attr {string} datatype 数字类型 text|bytetext|richtext1079 *1080 * @attr {integer} minlength 内容最小长度1081 * @attr {integer} maxlength 内容最大长度1082 * @example1083 <div class="f-l">1084 <input type="TEXT" name="company_name" minlength="2" maxlength="120" reqmsg="公司名称" errmsg="请检查格式,长度2-120" /> <em>公司名称描述</em>1085 </div>1086 */1087 , lengthValid: 1088 function( _item ){1089 var _p = this, _r = true1090 , _item = $( _item )1091 , _dt = _p.parseDatatype( _item )1092 , _min, _max1093 , _val = $.trim( _item.val() ), _len1094 ;1095 if( !_val ) return _r;1096 _p.isMinlength( _item ) && ( _min = _p.minlength( _item ) );1097 _p.isMaxlength( _item ) && ( _max = _p.maxlength( _item ) );1098 /**1099 * 根据特殊的 datatype 实现不同的计算方法1100 */1101 switch( _dt ){1102 case 'bytetext':1103 {1104 _len = _p.bytelen( _val );1105 break;1106 }1107 case 'richtext':1108 default:1109 {1110 _len = _val.length;1111 break;1112 }1113 }1114 _min && ( _len < _min ) && ( _r = false );1115 _max && ( _len > _max ) && ( _r = false );1116 //JC.log( 'lengthValid: ', _min, _max, _r, _val.length );1117 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1118 return _r;1119 }1120 /**1121 * 检查是否为正确的数字<br />1122 * <br>默认范围 0 - Math.pow(10, 10)1123 * @static1124 * @param {selector} _item1125 * @attr {require} datatype - n | n-整数位数.小数位数1126 * @attr {integer|optional} minvalue - 数值的下限1127 * @attr {integer|optional} maxvalue - 数值的上限1128 *1129 * @example1130 <div class="f-l">1131 <input type="TEXT" name="company_n" errmsg="请填写正确的正整数" datatype="n" >1132 </div>1133 <div class="f-l">1134 <input type="TEXT" name="company_n1" errmsg="请填写正确的数字, 范围1-100" datatype="n" minvalue="1", maxvalue="100" >1135 </div>1136 <div class="f-l">1137 <input type="TEXT" name="company_n2" errmsg="请填写正确的数字" datatype="n-7.2" >1138 </div>1139 *1140 */1141 , n: 1142 function( _item, _noError ){1143 var _p = this, _r = true1144 , _valStr = _item.val().trim()1145 , _val = +_valStr1146 ,_min = 01147 , _pow = 101148 , _max = Math.pow( 10, _pow )1149 , _n, _f, _tmp;1150 _p.isMinvalue( _item ) && ( _min = _p.minvalue( _item, /\./.test( _item.attr('minvalue') ) ) || _min );1151 if( /^[0]{2,}$/.test( _valStr ) ){1152 _r = false;1153 }1154 if( _r && !isNaN( _val ) && _val >= _min ){1155 _item.attr('datatype').replace( /^n[^\-]*\-(.*)$/, function( $0, $1 ){1156 _tmp = $1.split('.');1157 _n = parseInt( _tmp[0] );1158 _f = parseInt( _tmp[1] );1159 _n > _pow && ( _max = Math.pow( 10, _n ) );1160 });1161 //_p.isMaxvalue( _item ) && ( _max = _p.maxvalue( _item, /\./.test( _item.attr('maxvalue') ) ) || _max );1162 _p.isMaxvalue( _item ) && ( _max = _p.maxvalue( _item, /\./.test( _item.attr('maxvalue') ) ) );1163 if( _val >= _min && _val <= _max ){1164 typeof _n != 'undefined' 1165 && typeof _f != 'undefined' 1166 && ( _r = new RegExp( '^(?:\-|)(?:[\\d]{0,'+_n+'}|)(?:\\.[\\d]{1,'+_f+'}|)$' ).test( _valStr ) );1167 typeof _n != 'undefined' 1168 && typeof _f == 'undefined' 1169 && ( _r = new RegExp( '^(?:\-|)[\\d]{1,'+_n+'}$' ).test( _valStr ) );1170 typeof _n == 'undefined' 1171 && typeof _f != 'undefined' 1172 && ( _r = new RegExp( '^(?:\-|)\\.[\\d]{1,'+_f+'}$' ).test( _valStr ) );1173 typeof _f == 'undefined' && /\./.test( _valStr ) && ( _r = false );1174 } else _r = false;1175 //JC.log( 'n', _val, typeof _n, typeof _f, typeof _min, typeof _max, _min, _max );1176 }else _r = false;1177 !_r && !_noError && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1178 return _r;1179 }1180 /**1181 * 检查是否为正确的整数或者浮点数<br />1182 * <br>默认范围 0 - Math.pow(10, 10)1183 * @static1184 * @param {selector} _item1185 * @attr {require} datatype - f | f-整数位数.小数位数1186 * @attr {integer|optional} minvalue - 数值的下限1187 * @attr {integer|optional} maxvalue - 数值的上限1188 *1189 * @example1190 <div class="f-l">1191 <input type="TEXT" name="company_n" errmsg="请填写正确的正整数" datatype="f" >1192 </div>1193 <div class="f-l">1194 <input type="TEXT" name="company_n1" errmsg="请填写正确的数字, 范围1-100" datatype="f" minvalue="1", maxvalue="100" >1195 </div>1196 <div class="f-l">1197 <input type="TEXT" name="company_n2" errmsg="请填写正确的数字" datatype="f-7.2" >1198 </div>1199 *1200 */1201 , f: 1202 function( _item, _noError ){1203 var _p = this, _r = true1204 , _valStr = _item.val().trim()1205 , _val = +_valStr1206 ,_min = 01207 , _pow = 101208 , _max = Math.pow( 10, _pow )1209 , _n, _f, _tmp;1210 _p.isMinvalue( _item ) && ( _min = _p.minvalue( _item, /\./.test( _item.attr('minvalue') ) ) || _min );1211 if( /^[0]{2,}$/.test( _valStr ) ){1212 _r = false;1213 }1214 if( _r && !isNaN( _val ) && _val >= _min ){1215 _item.attr('datatype').replace( /^f[^\-]*\-(.*)$/, function( $0, $1 ){1216 _tmp = $1.split('.');1217 _n = parseInt( _tmp[0] );1218 _f = parseInt( _tmp[1] );1219 _n > _pow && ( _max = Math.pow( 10, _n ) );1220 });1221 typeof _n == 'undefined' && ( _n = 10 );1222 typeof _f == 'undefined' && ( _f = 2 );1223 _p.isMaxvalue( _item ) && ( _max = _p.maxvalue( _item, /\./.test( _item.attr('maxvalue') ) ) );1224 if( _val >= _min && _val <= _max ){1225 typeof _n != 'undefined' 1226 && typeof _f != 'undefined' 1227 && ( _r = new RegExp( '^(?:\-|)(?:[\\d]{0,'+_n+'}|)(?:\\.[\\d]{1,'+_f+'}|)$' ).test( _valStr ) );1228 typeof _n != 'undefined' 1229 && typeof _f == 'undefined' 1230 && ( _r = new RegExp( '^(?:\-|)[\\d]{1,'+_n+'}$' ).test( _valStr ) );1231 typeof _n == 'undefined' 1232 && typeof _f != 'undefined' 1233 && ( _r = new RegExp( '^(?:\-|)\\.[\\d]{1,'+_f+'}$' ).test( _valStr ) );1234 typeof _f == 'undefined' && /\./.test( _valStr ) && ( _r = false );1235 } else _r = false;1236 //JC.log( 'n', _val, typeof _n, typeof _f, typeof _min, typeof _max, _min, _max );1237 }else _r = false;1238 !_r && !_noError && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1239 return _r;1240 }1241 /**1242 * 检查两个输入框的数值1243 * <br /> 数字格式为 0-pow(10,10)1244 * <br /> 带小数点使用 nrange-int.float, 例: nrange-1.2 nrange-2.21245 * <br /> <b>注意:</b> 如果不显示指定 fromNEl, toNEl, 1246 * 将会从父级查找 datatype=nrange属性的input, 如果数量等于2, 则会进行验证, 不等2将忽略1247 * @static1248 * @param {selector} _item1249 * @attr {require} datatype - nrange1250 * @attr {selector|optional} fromNEl - 起始数值选择器1251 * @attr {selector|optional} toNEl - 结束数值选择器1252 * @attr {date string|optional} minvalue - 数值的下限1253 * @attr {date string|optional} maxvalue - 数值的上限1254 * @example1255 <div class="f-l label">1256 <label>(datatype nrange)正数:<br/><b style="color:red">注意: 这个是大小颠倒位置的nrange</b></label>1257 大<input type="text" name="company_n10" id="company_n10" fromNEl="company_n11"1258 errmsg="请填写正确的数值范围" datatype="nrange" emEl="nrange_n1011" >1259 - 小<input type="text" name="company_n11" id="company_n11" toNEl="company_n10"1260 errmsg="请填写正确的数值范围" datatype="nrange" emEl="nrange_n1011" >1261 <em id="nrange_n1011"></em>1262 </div>1263 */1264 , nrange:1265 function( _item ){1266 var _p = this, _r = _p.n( _item ), _min, _max, _fromNEl, _toNEl, _items, _tmp;1267 if( _r ){1268 if( _item.is( '[fromNEl]' ) ) {1269 _fromNEl = _p.getElement( _item.attr('fromNEl'), _item );1270 _toNEl = _item;1271 }1272 if( _item.is( '[toNEl]' ) ){1273 _fromNEl = _item;1274 _toNEl = _p.getElement( _item.attr('toNEl'), _item );1275 }1276 if( !(_fromNEl && _fromNEl.length || _toNEl && _toNEl.length) ){1277 _items = _p.sametypeitems( _item );1278 if( _items.length >= 2 ){1279 _fromNEl = $(_items[0]);1280 _toNEl = $(_items[1]);1281 }1282 }1283 if( _fromNEl && _fromNEl.length || _toNEl && _toNEl.length ){1284 //JC.log( 'nrange', _fromNEl.length, _toNEl.length );1285 _toNEl.val( $.trim( _toNEl.val() ) );1286 _fromNEl.val( $.trim( _fromNEl.val() ) );1287 if( _r && _toNEl && _toNEl.length && _toNEl.attr( 'subdatatype' ) && /\beven\b/.test( _toNEl.attr( 'subdatatype' ) ) ){1288 _r && ( _r = _p.even( _toNEl ) );1289 }1290 if( _r && _toNEl && _toNEl.length && _toNEl.attr( 'subdatatype' ) && /\bodd\b/.test( _toNEl.attr( 'subdatatype' ) ) ){1291 _r && ( _r = _p.odd( _toNEl ) );1292 }1293 if( _r && _fromNEl && _fromNEl.length && _fromNEl.attr( 'subdatatype' ) && /\beven\b/.test( _fromNEl.attr( 'subdatatype' ) ) ){1294 _r && ( _r = _p.even( _fromNEl ) );1295 }1296 if( _r && _fromNEl && _fromNEl.length && _fromNEl.attr( 'subdatatype' ) && /\bodd\b/.test( _fromNEl.attr( 'subdatatype' ) ) ){1297 _r && ( _r = _p.odd( _fromNEl ) );1298 }1299 if( !_r ){1300 return false;1301 }1302 1303 if( _toNEl[0] != _fromNEl[0] && _toNEl.val().length && _fromNEl.val().length ){1304 _r && ( _r = _p.n( _toNEl, true ) );1305 _r && ( _r = _p.n( _fromNEl, true ) );1306 _r && ( +_fromNEl.val() ) > ( +_toNEl.val() ) && ( _r = false );1307 _r && ( _tmp = _fromNEl.attr( 'rangeCanEqual' ) || _toNEl.attr( 'rangeCanEqual' ) )1308 && !JC.f.parseBool( _tmp )1309 && ( JC.f.parseFinance( _fromNEl.val(), 10 ) === JC.f.parseFinance( _toNEl.val(), 10 ) )1310 && ( _r = false );1311 ;1312 //JC.log( 'nrange:', +_fromNEl.val(), +_toNEl.val(), _r );1313 _r && $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, _fromNEl ] );1314 _r && $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, _toNEl ] );1315 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _fromNEl ] );1316 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _toNEl ] );1317 return _r;1318 }1319 }1320 }1321 return _r;1322 }1323 /**1324 * 检查是否为合法的日期,1325 * <br />日期格式为 YYYYMMDD, YYYY/MM/DD, YYYY-MM-DD, YYYY.MM.DD1326 * @param {selector} _item1327 * @attr {require} datatype - d1328 * @attr {date string|optional} minvalue - 日期的下限1329 * @attr {date string|optional} maxvalue - 日期的上限1330 * @example1331 <div class="f-l">1332 <input type="TEXT" name="company_d" errmsg="请填写正确的日期范围2013-05-01 - 2013-05-31" datatype="daterange" minvalue="2013-05-01" maxvalue="2013-05-31" >1333 </div>1334 */1335 , 'd': 1336 function( _item, _noError ){1337 var _p = this, _val = $.trim( _item.val() ), _r = true1338 , _date = JC.f.parseDate( _val, _item ), _tmpDate;1339 1340 if( _val && _date ){1341 if( _p.isMinvalue( _item ) && ( _tmpDate = _p.minvalue( _item, 'd' ) ) ){1342 _date.getTime() < _tmpDate.getTime() && ( _r = false );1343 }1344 if( _r && _p.isMaxvalue( _item ) && ( _tmpDate = _p.maxvalue( _item, 'd' ) ) ){1345 _date.getTime() > _tmpDate.getTime() && ( _r = false );1346 }1347 }else if( _val ){1348 _r = false;1349 }1350 !_r && !_noError && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1351 return _r;1352 }1353 , 'date': function(){ return this.d.apply( this, JC.f.sliceArgs( arguments ) ); }1354 , 'ddate': function(){ return this.d.apply( this, JC.f.sliceArgs( arguments ) ); }1355 /**1356 * 检查两个输入框的日期1357 * <br />日期格式为 YYYYMMDD, YYYY/MM/DD, YYYY-MM-DD, YYYY.MM.DD1358 * <br /> <b>注意:</b> 如果不显示指定 fromDateEl, toDateEl, 1359 * 将会从父级查找 datatype=daterange属性的input, 如果数量等于2, 则会进行验证, 不等2将忽略1360 * @param {selector} _item1361 * @attr {require} datatype - daterange1362 * @attr {selector|optional} fromDateEl - 起始日期选择器1363 * @attr {selector|optional} toDateEl - 结束日期选择器1364 * @attr {date string|optional} minvalue - 日期的下限1365 * @attr {date string|optional} maxvalue - 日期的上限1366 * @example1367 <div class="f-l">1368 <input type="TEXT" name="company_daterange" errmsg="请填写正确的日期范围,并且起始日期不能大于结束日期" id="start_date" 1369 datatype="daterange" toDateEl="end_date" emEl="date-err-em" >1370 - <input type="TEXT" name="company_daterange" errmsg="请填写正确的日期范围,并且起始日期不能大于结束日期" id="end_date" 1371 datatype="daterange" fromDateEl="start_date" emEl="date-err-em" >1372 <br /><em id="date-err-em"></em>1373 </div>1374 */1375 , daterange:1376 function( _item ){1377 var _p = this, _r = _p.d( _item ), _min, _max, _fromDateEl, _toDateEl, _items, _tmp, _datespan;1378 if( _r ){1379 if( _item.is( '[fromDateEl]' ) ) {1380 _fromDateEl = _p.getElement( _item.attr('fromDateEl'), _item );1381 _toDateEl = _item;1382 }1383 if( _item.is( '[toDateEl]' ) ){1384 _fromDateEl = _item;1385 _toDateEl = _p.getElement( _item.attr('toDateEl'), _item );1386 }1387 if( !(_fromDateEl && _fromDateEl.length && _toDateEl && _toDateEl.length) ){1388 _items = _p.sametypeitems( _item );1389 if( _items.length >= 2 ){1390 _fromDateEl = $(_items[0]);1391 _toDateEl = $(_items[1]);1392 }1393 }1394 if( _fromDateEl && _fromDateEl.length || _toDateEl && _toDateEl.length ){1395 //JC.log( 'daterange', _fromDateEl.length, _toDateEl.length );1396 _toDateEl.val( $.trim( _toDateEl.val() ) );1397 _fromDateEl.val( $.trim( _fromDateEl.val() ) );1398 if( _toDateEl[0] != _fromDateEl[0] && _toDateEl.val().length && _fromDateEl.val().length ){1399 _r && ( _r = _p.d( _toDateEl, true ) ) && ( _min = JC.f.parseDate( _fromDateEl.val(), _fromDateEl ) );1400 _r && ( _r = _p.d( _fromDateEl, true ) ) && ( _max = JC.f.parseDate( _toDateEl.val(), _toDateEl ) );1401 _r && _min && _max 1402 && _min.getTime() > _max.getTime() 1403 && ( _r = false );1404 if( _r && _min && _max ){1405 _datespan = ( _fromDateEl.attr( 'datespan' ) || _toDateEl.attr( 'datespan' ) );1406 if( _datespan && ( _datespan = JC.f.dateDetect( JC.f.formatISODate( _min ) + _datespan ) ) ){1407 if( _max.getTime() > _datespan.getTime() ){1408 _r = false;1409 }1410 }1411 }1412 _r && ( _tmp = _fromDateEl.attr( 'rangeCanEqual' ) || _toDateEl.attr( 'rangeCanEqual' ) )1413 && !JC.f.parseBool( _tmp )1414 && _min && _max1415 && _min.getTime() == _max.getTime()1416 && ( _r = false );1417 ;1418 _r && $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, _fromDateEl ] );1419 _r && $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, _toDateEl ] );1420 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _fromDateEl ] );1421 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _toDateEl ] );1422 }1423 }1424 }1425 return _r;1426 }1427 , 'drange': function(){ return this.daterange.apply( this, JC.f.sliceArgs( arguments ) ); }1428 /**1429 * 检查时间格式, 格式为 hh:mm:ss1430 * @param {selector} _item1431 * @example1432 <div class="f-l">1433 <input type="TEXT" name="company_time" errmsg="正确的时间, 格式为 hh:mm:ss" datatype="time" >1434 </div>1435 */1436 , time: 1437 function( _item ){1438 var _p = this, _r = /^(([0-1]\d)|(2[0-3])):[0-5]\d:[0-5]\d$/.test( _item.val() );1439 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1440 return _r;1441 }1442 /**1443 * 检查时间格式, 格式为 hh:mm1444 * @param {selector} _item1445 * @example1446 <div class="f-l">1447 <input type="TEXT" name="company_time" errmsg="正确的时间, 格式为 hh:mm" datatype="minute" >1448 </div>1449 */1450 , minute: 1451 function( _item ){1452 var _p = this, _r = /^(([0-1]\d)|(2[0-3])):[0-5]\d$/.test( _item.val() );1453 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1454 return _r;1455 }1456 /**1457 * 检查银行卡号码1458 * <br />格式为: d{15}, d{16}, d{17}, d{19}1459 * @param {selector} _item1460 * @example1461 <div class="f-l">1462 <input type="TEXT" name="company_idnumber" 1463 datatype="idnumber" errmsg="请填写正确的身份证号码">1464 </div>1465 */1466 , bankcard:1467 function( _item ){1468 var _p = this1469 , _v = _item.val().trim().replace(/[\s]+/g, ' ')1470 ;1471 _item.val( _v );1472 var _dig = _v.replace( /[^\d]/g, '' )1473 , _r = /^[0-9](?:[\d]{24}|[\d]{23}|[\d]{22}|[\d]{21}|[\d]{20}|[\d]{19}|[\d]{18}|[\d]{17}|[\d]{16}|[\d]{15}|[\d]{14}|[\d]{13}|[\d]{12}|[\d]{11}|[\d]{10}|[\d]{9}|[\d]{8}|)$/.test( _dig )1474 ;1475 /^[0]+$/.test( _dig ) && ( _r = false );1476 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1477 return _r;1478 }1479 /**1480 * 检查中文姓名1481 * <br>格式: 汉字和大小写字母1482 * <br>规则: 长度 2-32个字节, 非 ASCII 算2个字节1483 * @param {selector} _item1484 * @example1485 <div class="f-l">1486 <input type="TEXT" name="company_cnname" 1487 datatype="cnname" reqmsg="姓名" errmsg="请填写正确的姓名">1488 </div>1489 */1490 , cnname:1491 function( _item, _noStatus ){1492 var _p = this1493 , _r = _p.bytelen( _item.val() ) <= 32 && /^[\u4e00-\u9fa5a-zA-Z.\u3002\u2022]{2,32}$/.test( _item.val() );1494 !_noStatus && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1495 return _r;1496 }1497 /**1498 * 检查英文1499 * <br>格式: 大小写字母 + 空格1500 * <br>规则: 长度 2-32个字节, 非 ASCII 算2个字节1501 * @param {selector} _item1502 * @example1503 <div class="f-l">1504 <input type="TEXT" name="company_enname" 1505 datatype="enname" reqmsg="姓名" errmsg="请填写正确的姓名">1506 </div>1507 */1508 , enname:1509 function( _item, _noStatus ){1510 var _p = this1511 , _r = _p.bytelen( _item.val() ) <= 32 && /^[a-zA-Z ]{2,32}$/.test( _item.val() );1512 !_noStatus && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1513 return _r;1514 }1515 /**1516 * 检查 英文名称/中文名称1517 * <br>allname = cnname + enname1518 * <br>规则: 长度 2-32个字节, 非 ASCII 算2个字节1519 * @param {selector} _item1520 * @example1521 <div class="f-l">1522 <input type="TEXT" name="company_allname" 1523 datatype="allname" reqmsg="姓名" errmsg="请填写正确的姓名">1524 </div>1525 */1526 , allname:1527 function( _item ){1528 var _p = this1529 , _r = _p.bytelen( _item.val() ) <= 32 1530 && ( _p.cnname( _item, true ) || _p.enname( _item, true ) )1531 ;1532 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1533 return _r;1534 }1535 /**1536 * 检查注册用户名1537 * <br>格式: a-zA-Z0-9_-1538 * <br>规则: 首字母必须为 [a-zA-Z0-9], 长度 2 - 301539 * @param {selector} _item1540 * @example1541 <div class="f-l">1542 <input type="TEXT" name="company_username" 1543 datatype="username" reqmsg="用户名" errmsg="请填写正确的用户名">1544 </div>1545 */1546 , username:1547 function( _item ){1548 var _p = this, _r = /^[a-zA-Z0-9][\w-]{2,30}$/.test( _item.val() );1549 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1550 return _r;1551 }1552 /**1553 * 检查身份证号码<br />1554 * 目前只使用最简单的位数判断~ 有待完善1555 * @param {selector} _item1556 * @example1557 <div class="f-l">1558 <input type="TEXT" name="company_idnumber" 1559 datatype="idnumber" errmsg="请填写正确的身份证号码">1560 </div>1561 */1562 , idnumber:1563 function( _item ){1564 var _p = this, _r = /^[0-9]{15}(?:[0-9]{2}(?:[0-9xX])|)$/.test( _item.val() );1565 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1566 return _r;1567 }1568 /**1569 * 检查QQ号码( 5 ~ 11位数字 )1570 * @param {selector} _item1571 * @param {bool} _noError1572 * @example1573 <div class="f-l">1574 <input type="TEXT" name="qq" 1575 datatype="qq" 1576 errmsg="请填写正确的qq号码">1577 </div>1578 */1579 , qq: 1580 function( _item, _noError ){1581 var _p = this, _r = /^[1-9][\d]{4,10}$/.test( _item.val() );1582 !_noError && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1583 return _r;1584 }1585 /**1586 * 检查QQ号码( 数字号码|电子邮件 )1587 * <br />5 ~ 11位数字1588 * @param {selector} _item1589 * @param {bool} _noError1590 * @example1591 <div class="f-l">1592 <input type="TEXT" name="qqall" 1593 datatype="qqall" 1594 errmsg="请填写正确的qq号码">1595 </div>1596 */1597 , qqall: 1598 function( _item, _noError ){1599 var _p = this, _r = _p.qq( _item, true ) || _p.email( _item, true );1600 !_noError && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1601 return _r;1602 }1603 /**1604 * 检查手机号码<br />1605 * @param {selector} _item1606 * @param {bool} _noError1607 * @example1608 <div class="f-l">1609 <input type="TEXT" name="company_mobile" 1610 datatype="mobilecode" subdatatype="alternative" datatarget="input[name=company_phonecode]" alternativemsg=" "1611 errmsg="请填写正确的手机号码">1612 </div>1613 */1614 , mobilecode: 1615 function( _item, _noError ){1616 var _p = this, _r = /^(?:13|14|15|16|17|18|19)[\d]{9}$/.test( _item.val() );1617 !_noError && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1618 return _r;1619 }1620 /**1621 * 检查手机号码1622 * <br />这个方法是 mobilecode 的别名1623 * @param {selector} _item1624 * @param {bool} _noError1625 */1626 , mobile:1627 function( _item, _noError ){1628 return this.mobilecode( _item, _noError );1629 }1630 /**1631 * 检查手机号码加强方法1632 * <br>格式: [+国家代码] [零]11位数字1633 * @param {selector} _item1634 * @param {bool} _noError1635 * @example1636 <div class="f-l">1637 <input type="TEXT" name="company_mobilezone" 1638 datatype="mobilezonecode" 1639 errmsg="请填写正确的手机号码">1640 </div>1641 */1642 , mobilezonecode: 1643 function( _item, _noError ){1644 var _p = this, _r = /^(?:\+[0-9]{1,6} |)(?:0|)(?:13|14|15|16|17|18|19)\d{9}$/.test( _item.val() );1645 !_noError && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1646 return _r;1647 }1648 /**1649 * 检查电话号码1650 * <br>格式: 7/8位数字1651 * @param {selector} _item1652 * @example1653 <div>1654 <input type='TEXT' name='company_phonecode' style="width:80px;" value='' size="8" 1655 datatype="phonecode" errmsg="请检查电话号码格式" emEl="#phone-err-em" />1656 </div>1657 */1658 , phonecode: 1659 function( _item ){1660 var _p = this, _r = /^[1-9][0-9]{6,7}$/.test( _item.val() );1661 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1662 return _r;1663 }1664 /**1665 * 检查电话号码1666 * <br>格式: [区号]7/8位电话号码1667 * @param {selector} _item1668 * @param {bool} _noError1669 * @example1670 <div class="f-l">1671 <input type="TEXT" name="company_phone" 1672 datatype="phone" 1673 errmsg="请填写正确的电话号码">1674 </div>1675 */1676 , phone:1677 function( _item, _noError ){1678 var _p = this, _r = /^(?:0(?:10|2\d|[3-9]\d\d)(?: |\-|)|)[1-9][\d]{6,7}$/.test( _item.val() );1679 !_noError && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1680 return _r;1681 }1682 /**1683 * 检查电话号码1684 * <br>格式: [+国家代码][ ][电话区号][ ]7/8位电话号码[#分机号]1685 * @param {selector} _item1686 * @param {bool} _noError1687 * @example1688 <div class="f-l">1689 <input type="TEXT" name="company_mobilezone" 1690 datatype="phoneall" 1691 errmsg="请填写正确的电话号码">1692 </div>1693 */1694 , phoneall:1695 function( _item, _noError ){1696 var _p = this1697 , _r = /^(?:\+[\d]{1,6}(?: |\-)|)(?:0[\d]{2,3}(?:\-| |)|)[1-9][\d]{6,7}(?:(?: |)(?:\#|\-)[\d]{1,6}|)$/.test( _item.val() );1698 !_noError && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1699 return _r;1700 }1701 /**1702 * 检查电话区号1703 * @param {selector} _item1704 * @example1705 <div>1706 <input type='TEXT' name='company_phonezone' style="width:40px;" value='' size="4" 1707 datatype="phonezone" emEl="#phone-err-em" errmsg="请填写正确的电话区号" />1708 </div>1709 */1710 , phonezone: 1711 function( _item ){1712 var _p = this, _v = _item.val().trim(), _r, _re = /^[0-9]{3,4}$/, _pattern;1713 _pattern = _item.attr('datatype').split('-');1714 _pattern.length > 1 && ( _re = new RegExp( '^[0-9]{' + _pattern[1] + '}$' ) );1715 _r = _re.test( _v );1716 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1717 return _r;1718 }1719 /**1720 * 检查电话分机号码1721 * @param {selector} _item1722 * @example1723 <div>1724 <input type='TEXT' name='company_phoneext' style="width:40px;" value='' size="4" 1725 datatype="phoneext" emEl="#phone-err-em" errmsg="请填写正确的分机号" />1726 </div>1727 */1728 , phoneext: 1729 function( _item ){1730 var _p = this, _r = /^[0-9]{1,6}$/.test( _item.val() );1731 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1732 return _r;1733 }1734 /**1735 * 检查手机号码/电话号码1736 * <br />这个方法是原有方法的混合验证 mobilecode + phone1737 * @param {selector} _item1738 * @example1739 <div class="f-l label">1740 <label>(datatype mobilephone, phone + mobilecode)手机号码或电话号码:</label>1741 </div>1742 <div class="f-l">1743 <input type="text" name="company_mobilephone" 1744 datatype="mobilephone"1745 errmsg="请填写正确的手机/电话号码">1746 </div>1747 */1748 , mobilephone:1749 function( _item ){1750 var _p = this, _r = this.mobilecode( _item, true ) || this.phone( _item, true );1751 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1752 return _r;1753 }1754 /**1755 * 检查手机号码/电话号码, 泛匹配1756 * <br />这个方法是原有方法的混合验证 mobilezonecode + phoneall1757 * @param {selector} _item1758 * @example1759 <div class="f-l label">1760 <label>(datatype mobilephoneall, phoneall + mobilezonecode)手机号码或电话号码:</label>1761 </div>1762 <div class="f-l">1763 <input type="text" name="company_mobilephoneall" 1764 datatype="mobilephoneall"1765 errmsg="请填写正确的手机/电话号码">1766 </div>1767 */1768 , mobilephoneall:1769 function( _item ){1770 var _p = this, _r = this.mobilezonecode( _item, true ) || this.phoneall( _item, true );1771 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1772 return _r;1773 }1774 /**1775 * 自定义正则校验1776 * @param {selector} _item1777 * @attr {string} reg-pattern 正则规则 /规则/选项1778 * @example1779 <div><input type="TEXT" name="company_addr" datatype="reg" reg-pattern="/^[\s\S]{2,120}$/i" errmsg="请填写正确的地址"></div>1780 <div><input type="TEXT" name="company_addr" datatype="reg-/^[\s\S]{2,120}$/i" errmsg="请填写正确的地址"></div>1781 */1782 , reg: 1783 function( _item ){1784 var _p = this, _r = true, _pattern;1785 if( _item.is( '[reg-pattern]' ) ) _pattern = _item.attr( 'reg-pattern' );1786 if( !_pattern ) _pattern = $.trim(_item.attr('datatype')).replace(/^reg(?:\-|)/i, '');1787 _pattern.replace( /^\/([\s\S]*)\/([\w]{0,3})$/, function( $0, $1, $2 ){1788 //JC.log( $1, $2 );1789 _r = new RegExp( $1, $2 || '' ).test( _item.val() );1790 });1791 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1792 return _r;1793 }1794 /**1795 * 检查验证码<br />1796 * 格式: 为 0-9a-zA-Z, 长度 默认为41797 * @param {selector} _item1798 * @attr {string} datatype vcode|vcode-[\d]+1799 * @example1800 <div class="f-l">1801 <input type="TEXT" name="company_vcode" style="width: 40px;"1802 datatype="vcode" reqmsg="验证码" errmsg="请填写正确的验证码">1803 </div>1804 <div class="f-l">1805 <input type="TEXT" name="company_vcode" style="width: 40px;"1806 datatype="vcode-5" errmsg="请填写正确的验证码">1807 </div>1808 */1809 , vcode:1810 function( _item ){1811 var _p = this, _r, _len = parseInt( $.trim(_item.attr('datatype')).replace( /^vcode(?:\-|)/i, '' ), 10 ) || 4; 1812 //JC.log( 'vcodeValid: ' + _len );1813 _r = new RegExp( '^[0-9a-zA-Z]{'+_len+'}$' ).test( _item.val() );1814 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1815 return _r;1816 }1817 /**1818 * 检查文本长度1819 * @see length1820 * @attr {string} datatype text1821 */1822 , text: function(_item){ return true; }1823 /**1824 * 检查文本的字节长度1825 * @see length1826 * @attr {string} datatype bytetext1827 */1828 , bytetext: function(_item){ return true; }1829 /**1830 * 检查富文本的字节1831 * <br />TODO: 完成富文本长度检查1832 * @see length1833 * @attr {string} datatype richtext1834 */1835 , richtext: function(_item){ return true; }1836 /**1837 * 计算字符串的字节长度, 非 ASCII 0-255的字符视为两个字节1838 * @param {string} _s1839 */1840 , bytelen: 1841 function( _s ){1842 return _s.replace(/[^\x00-\xff]/g,"11").length;1843 }1844 /**1845 * 检查URL1846 * @param {selector} _item1847 * @example1848 <div class="f-l">1849 <input type="TEXT" name="company_url" datatype="url" errmsg="请填写正确的网址">1850 </div>1851 */1852 , url: 1853 function( _item ){1854 var _p = this1855 //, _r = /^((http|ftp|https):\/\/|)[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])$/.test( _item.val() )1856 //, _r = /^(?:htt(?:p|ps)\:\/\/|)((?:(?:(?:\w[\.\-\+]*))\w)*)((?:(?:(?:\w[\.\-\+]*){0,62})\w)+)\.([a-z]{2,6})(?:\/[\w\/\.\#\+\-\~\%\?\_\=\&]*|)$/i.test( _item.val() )1857 , _r = /^(?:htt(?:p|ps)\:\/\/|)((?:(?:(?:\w[\.\-\+]*))\w)*)((?:(?:(?:\w[\.\-\+]*){0,62})\w)+)\.([a-z]{2,6})(?:\/[^\s<>]*|)$/i.test( _item.val() )1858 ;1859 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1860 return _r;1861 }1862 /**1863 * 检查域名1864 * @param {selector} _item1865 <div class="f-l">1866 <input type="TEXT" name="company_domain" datatype="domain" reqmsg="域名" errmsg="请填写正确的域名">1867 </div>1868 */1869 , domain:1870 function( _item ){1871 //var _r = /^(?:(?:f|ht)tp\:\/\/|)((?:(?:(?:\w[\.\-\+]?)*)\w)*)((?:(?:(?:\w[\.\-\+]?){0,62})\w)+)\.(\w{2,6})(?:\/|)$/.test( _item.val() );1872 var _p = this1873 , _r = /^(?:htt(?:p|ps)\:\/\/|)((?:(?:(?:\w[\.\-\+]*))\w)*)((?:(?:(?:\w[\.\-\+]*){0,62})\w)+)\.([a-z]{2,6})(?:\/|)$/i.test( _item.val() );1874 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1875 return _r;1876 }1877 /**1878 * 检查域名1879 * @param {selector} _item1880 <div class="f-l">1881 <input type="TEXT" name="company_domain" datatype="stricdomain" reqmsg="域名" errmsg="请填写正确的域名">1882 </div>1883 */1884 , stricdomain:1885 function( _item ){1886 var _p = this1887 , _r = /^((?:(?:(?:\w[\.\-\+]*))\w)*)((?:(?:(?:\w[\.\-\+]*){0,62})\w)+)\.([a-z]{2,6})$/i.test( _item.val() );1888 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1889 return _r;1890 }1891 /**1892 * 检查电子邮件1893 * @param {selector} _item1894 * @example1895 <div class="f-l">1896 <input type="TEXT" name="company_email" datatype="email" reqmsg="邮箱" errmsg="请填写正确的邮箱">1897 </div>1898 */1899 , email: 1900 function( _item, _noError ){1901 var _p = this, _r = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i.test( _item.val() );1902 !_noError && !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1903 return _r;1904 }1905 /**1906 * 检查地区代码1907 * @param {selector} _item1908 * @example1909 <div class="f-l">1910 <input type="TEXT" name="company_countrycode" datatype="countrycode" errmsg="请填写正确的地区代码">1911 </div>1912 */1913 , countrycode: 1914 function( _item ){1915 var _p = this, _v = _item.val().trim(), _r = /^(?:\+|)[\d]{1,6}$/.test( _v );1916 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1917 return _r;1918 }1919 /**1920 * 检查邮政编码1921 * @param {selector} _item1922 * @example1923 <div class="f-l">1924 <input type="TEXT" name="company_zipcode" datatype="zipcode" errmsg="请填写正确的邮编">1925 </div>1926 */1927 , zipcode: 1928 function( _item ){1929 var _p = this, _r = /^[0-9]{6}$/.test( _item.val() );1930 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1931 return _r;1932 }1933 /**1934 * 纳税人识别号, 15, 18, 20位字符1935 * @param {selector} _item1936 * @example1937 <div class="f-l">1938 <input type="TEXT" name="" datatype="taxcode" errmsg="请填空正确的纳税人识别号">1939 </div>1940 */1941 , taxcode: 1942 function( _item ){1943 var _p = this, _r = false, _v = _item.val().trim();1944 _r = /^[\w]{15}$/.test( _v ) 1945 || /^[\w]{18}$/.test( _v ) 1946 || /^[\w]{20}$/.test( _v ) 1947 ;1948 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );1949 return _r;1950 }1951 /**1952 * 此类型检查 2|N 个对象填写的值必须一致1953 * 常用于注意时密码验证/重置密码1954 * @param {selector} _item1955 * @example1956 <dd>1957 <div class="f-l label">1958 <label>(datatype text, subdatatype reconfirm)用户密码:</label>1959 </div>1960 <div class="f-l">1961 <input type="PASSWORD" name="company_pwd" 1962 datatype="text" subdatatype="reconfirm" datatarget="input[name=company_repwd]" reconfirmmsg="用户密码和确认密码不一致"1963 minlength="6" maxlength="15" reqmsg="用户密码" errmsg="请填写正确的用户密码">1964 </div>1965 </dd>1966 <dd>1967 <div class="f-l label">1968 <label>(datatype text, subdatatype reconfirm)确认密码:</label>1969 </div>1970 <div class="f-l">1971 <input type="PASSWORD" name="company_repwd" 1972 datatype="text" subdatatype="reconfirm" datatarget="input[name=company_pwd]" reconfirmmsg="确认密码和用户密码不一致"1973 minlength="6" maxlength="15" reqmsg="确认密码" errmsg="请填写正确的确认密码">1974 </div>1975 </dd>1976 */1977 , reconfirm:1978 function( _item ){1979 var _p = this1980 , _r = true1981 , _target1982 , _KEY = "ReconfirmValidTime"1983 , _typeKey = 'reconfirm'1984 ;1985 //JC.log( _typeKey, new Date().getTime() );1986 _p.isDatatarget( _item, _typeKey ) && (_target = _p.datatarget( _item, _typeKey ) );1987 !( _target && _target.length ) && ( _target = _p.samesubtypeitems( _item, _typeKey ) );1988 var _isReturn = false;1989 if( _target && _target.length ){1990 _target.each( function(){ 1991 var _sp = $(this);1992 if( _p.checkRepeatProcess( _sp, _KEY, true ) ) {1993 _isReturn = true;1994 }1995 if( _item.val() != $(this).val() ) _r = false; 1996 } );1997 }1998 !_r && _target.length && _target.each( function(){ 1999 if( _item[0] == this ) return;2000 $(_p).trigger( Model.TRIGGER, [ Model.ERROR, $(this), 'reconfirmmsg', true ] );2001 } );2002 if( _r && _target && _target.length ){2003 _target.each( function(){2004 if( _item[0] == this ) return;2005 if( _isReturn ) return false;2006 $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, $(this) ] );2007 });2008 }2009 !_r && _item.attr( 'datatypestatus', 'false' );2010 _r 2011 ? $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, _item ] )2012 : $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item, 'reconfirmmsg', true ] )2013 ;2014 return _r;2015 }2016 , checkRepeatProcess:2017 function( _item, _key, _setTime, _tm ){2018 var _time = new Date().getTime(), _r = false;2019 _tm = _tm || 200;2020 if( _item.data( _key ) ){2021 if( (_time - _item.data( _key ) ) < _tm ){2022 _r = true;2023 _item.data( _key, _time );2024 }2025 }2026 _setTime && _item.data( _key, _time );2027 return _r;2028 }2029 /**2030 * 此类型检查 2|N个对象必须至少有一个是有输入内容的, 2031 * <br> 常用于 手机/电话 二填一2032 * @param {selector} _item2033 * @example2034 <dd>2035 <div class="f-l label">2036 <label>(datatype phonezone, phonecode, phoneext)电话号码:</label>2037 </div>2038 <div class="f-l">2039 <input type='TEXT' name='company_phonezone' style="width:40px;" value='' size="4" 2040 datatype="phonezone" emEl="#phone-err-em" errmsg="请填写正确的电话区号" />2041 - <input type='TEXT' name='company_phonecode' style="width:80px;" value='' size="8" 2042 datatype="phonecode" subdatatype="alternative" datatarget="input[name=company_mobile]" alternativemsg="电话号码和手机号码至少填写一个"2043 errmsg="请检查电话号码格式" emEl="#phone-err-em" />2044 - <input type='TEXT' name='company_phoneext' style="width:40px;" value='' size="4" 2045 datatype="phoneext" emEl="#phone-err-em" errmsg="请填写正确的分机号" />2046 <em id="phone-err-em"></em>2047 </div>2048 </dd>2049 <dd>2050 <div class="f-l label">2051 <label>(datatype mobilecode)手机号码:</label>2052 </div>2053 <div class="f-l">2054 <input type="TEXT" name="company_mobile" 2055 datatype="mobilecode" subdatatype="alternative" datatarget="input[name=company_phonecode]" alternativemsg=" "2056 errmsg="请填写正确的手机号码">2057 </div>2058 </dd>2059 */2060 , alternative:2061 function( _item ){2062 var _p = this2063 , _r = true2064 , _target2065 , _KEY = "AlternativeValidTime"2066 , _dt = _p.parseDatatype( _item )2067 , _typeKey = 'alternative'2068 ;2069 //JC.log( _typeKey, new Date().getTime() );2070 _p.isDatatarget( _item, _typeKey ) && (_target = _p.datatarget( _item, _typeKey ) );2071 !( _target && _target.length ) && ( _target = _p.samesubtypeitems( _item, _typeKey ) );2072 var _isReturn = false;2073 var _reqTarget;2074 if( _target.length && !$.trim( _item.val() ) ){2075 var _hasVal = false;2076 _target.each( function(){ 2077 var _sp = $(this);2078 if( _item[0] == this ) return;2079 if( _p.checkRepeatProcess( _sp, _KEY, true ) ) {2080 _isReturn = true;2081 }2082 if( $(this).val() ){ 2083 _hasVal = true; return false; 2084 } 2085 } );2086 _r = _hasVal;2087 }2088 !_r && _target && _target.length 2089 && _target.each( function(){ 2090 if( _item[0] == this ) return;2091 if( _isReturn ) return false;2092 $(_p).trigger( Model.TRIGGER, [ Model.ERROR, $(this), 'alternativemsg', true ] );2093 });2094 if( _r && _target && _target.length ){2095 _target.each( function(){2096 if( _item[0] == this ) return;2097 var _sp = $(this), _sdt = _p.parseDatatype( _sp );2098 if( _sdt && _p[ _sdt ] && $(this).val() ){2099 _p[ _sdt ]( $(this) );2100 }else if( !$(this).val() ){2101 $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, $(this) ] );2102 var _reqTarget = JC.f.parentSelector( $(this), $(this).attr( 'reqtargetdatatarget' ) );2103 _reqTarget 2104 && _reqTarget.length2105 && $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, _reqTarget ] )2106 ;2107 }2108 });2109 }2110 if( _r && _target && _target.length ){2111 var _hasReqTarget = false, _reqErrList = [];2112 _target.each( function(){2113 if( _item[0] == this ) return;2114 var _sp = $(this), _reqTarget;2115 if( _sp.is( '[alternativeReqTarget]' ) ){2116 _reqTarget = JC.f.parentSelector( _sp, _sp.attr('alternativeReqTarget') );2117 if( _reqTarget && _reqTarget.length ){2118 _reqTarget.each( function(){2119 var _ssp = $(this), _v = _ssp.val().trim();2120 if( !_v ){2121 _reqErrList.push( _ssp );2122 _hasReqTarget = true;2123 }2124 });2125 }2126 }2127 });2128 if( _item.is( '[alternativeReqTarget]' ) ){2129 _reqTarget = JC.f.parentSelector( _item, _item.attr('alternativeReqTarget') );2130 if( _reqTarget && _reqTarget.length ){2131 _reqTarget.each( function(){2132 var _ssp = $(this), _v = _ssp.val().trim();2133 if( !_v ){2134 _reqErrList.push( _ssp );2135 _hasReqTarget = true;2136 }2137 });2138 }2139 }2140 //alert( _hasReqTarget + ', ' + _reqErrList.length );2141 if( _hasReqTarget && _reqErrList.length ){2142 _r = false;2143 $.each( _reqErrList, function( _ix, _sitem ){2144 _sitem = $( _sitem );2145 $( _p ).trigger( Model.TRIGGER, [ Model.ERROR, _sitem, 'alternativeReqmsg', true ] );2146 });2147 return _r;2148 }2149 }2150 if( _r ){2151 if( _dt && _p[ _dt ] && _item.val() ){2152 _p[ _dt ]( _item );2153 }else if( !_item.val() ){2154 $(_p).trigger( Model.TRIGGER, [ Model.CORRECT, _item ] );2155 }2156 }else{2157 !_r && _item.attr( 'datatypestatus', 'false' );2158 $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item, 'alternativemsg', true ] );2159 }2160 return _r;2161 }2162 /**2163 * 如果 _item 的值非空, 那么 reqtarget 的值也不能为空2164 * @param {selector} _item2165 */2166 , 'reqtarget':2167 function( _item ){2168 var _p = this, _r = true2169 , _v = _item.val().trim(), _tv2170 , _target = JC.f.parentSelector( _item, _item.attr('reqtargetdatatarget') || _item.attr('datatarget') )2171 ;2172 if( _v && _target && _target.length ){2173 _tv = _target.val().trim();2174 !_tv && ( _r = false );2175 !_r && _item.attr( 'datatypestatus', 'false' );2176 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _target, 'reqtargetmsg', true ] );2177 _r && _target.trigger('blur');2178 }else if( _target && _target.length ){2179 _target.trigger('blur');2180 }2181 return _r;2182 }2183 /**2184 * 数值必须为偶数2185 * @param {selector} _item2186 */2187 , 'even':2188 function( _item ){2189 var _p = this, _r = true2190 , _v = JC.f.parseFinance( _item.val().trim(), 9 ) || 02191 ;2192 if( isNaN( _v ) ){2193 _r = false;2194 }else if( _v % 2 !== 0 ){2195 _r = false;2196 }2197 !_r && JC.log( 'even:', _r, JC.f.gid() );2198 //!_r && _item.attr( 'datatypestatus', 'false' );2199 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item, 'evenmsg', true ] );2200 return _r;2201 }2202 /**2203 * 数值必须为奇数2204 * @param {selector} _item2205 */2206 , 'odd':2207 function( _item ){2208 var _p = this, _r = true2209 , _v = JC.f.parseFinance( _item.val().trim(), 9 ) || 02210 ;2211 if( isNaN( _v ) ){2212 _r = false;2213 }else if( _v % 2 === 0 ){2214 _r = false;2215 }2216 //!_r && _item.attr( 'datatypestatus', 'false' );2217 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item, 'oddmsg', true ] );2218 return _r;2219 }2220 , ucheck:2221 function( _item ){2222 var _r = true, _p = this;2223 this.ucheckCallback( _item ) && ( _r = this.ucheckCallback( _item )( _item ) );2224 !_r && _item.attr( 'datatypestatus', 'false' );2225 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item, 'ucheckmsg', true ] );2226 return _r;2227 }2228 , ucheckCallback:2229 function( _item ){2230 var _r;2231 if( _item && _item.length && _item.is( '[ucheckCallback]' ) ){2232 _r = window[ _item.attr( 'ucheckCallback' ) ];2233 }2234 return _r;2235 }2236 /**2237 * N 个值必须保持唯一性, 不能有重复2238 * @param {selector} _item2239 */2240 , 'unique':2241 function( _item ){2242 var _p = this, _r = true2243 , _target, _tmp, _group = []2244 , _len = _p.typeLen( _item.attr('subdatatype') )[0]2245 , _KEY = "UniqueValidTime"2246 , _typeKey = 'unique'2247 , _ignoreCase = JC.f.parseBool( _item.attr('uniqueIgnoreCase') )2248 , _errLs, _corLs2249 ;2250 //JC.log( _typeKey, new Date().getTime() );2251 _p.isDatatarget( _item, _typeKey ) && (_target = _p.datatarget( _item, _typeKey ) );2252 !( _target && _target.length ) && ( _target = _p.samesubtypeitems( _item, _typeKey ) );2253 //JC.log( _target && _target.length ? _target.length : 'null' );2254 _errLs = [];2255 _corLs = [];2256 var _isReturn = false;2257 if( _target && _target.length ){2258 _tmp = {};2259 _target.each( function( _ix ){2260 var _sp = $(this);2261 if( _sp.is('[processDisabled]') 2262 && ( !_sp.attr('processDisabled') 2263 || JC.f.parseBool( _sp.attr('processDisabled' ) ) 2264 )2265 ){2266 if( !( _sp.is(':visible') || _p.isValidHidden( _sp ) ) ) return;2267 }else{2268 if( ! _p.isAvalible( _sp ) ) return;2269 }2270 if( _p.checkRepeatProcess( _sp, _KEY, true ) ) {2271 _isReturn = true;2272 //return false;2273 }2274 //JC.log( _ix, _sp.val() );2275 if( _ix % _len === 0 ){2276 _group.push( [] );2277 }2278 _group[ _group.length - 1 ] 2279 && _group[ _group.length - 1 ].push( _sp )2280 ; 2281 });2282 //if( _isReturn ) return _r;2283 $.each( _group, function( _ix, _items ){2284 var _tmpAr = [], _ignoreEmpty = false;2285 $.each( _items, function( _six, _sitem ){2286 var _tmpV, _ignore = JC.f.parseBool( _sitem.attr('uniqueIgnoreEmpty') );2287 _tmpV = $(_sitem).val().trim();2288 _ignore && !_tmpV && ( _sitem.is(':visible') || _p.isValidHidden( _sitem ) ) && ( _ignoreEmpty = true );2289 _tmpAr.push( _tmpV );2290 });2291 var _pureVal = _tmpAr.join(''), _compareVal = _tmpAr.join('####');2292 if( _ignoreEmpty ) return;2293 if( !_pureVal ) return;2294 _ignoreCase && ( _compareVal = _compareVal.toLowerCase() );2295 //JC.log( _compareVal );2296 if( _compareVal in _tmp ){2297 _tmp[ _compareVal ].push( _items );2298 _r = false;2299 }else{2300 _tmp[ _compareVal ] = [ _items ];2301 }2302 });2303 for( var _k in _tmp ){2304 if( _tmp[ _k ].length > 1 ){2305 _r = false;2306 $.each( _tmp[ _k ], function( _ix, _items ){2307 _errLs = _errLs.concat( _items ) ;2308 });2309 }else{2310 $.each( _tmp[ _k ], function( _ix, _items ){2311 _corLs = _corLs.concat( _items ) ;2312 });2313 }2314 }2315 }2316 //if( _isReturn ) return _r;2317 $.each( _corLs, function( _ix, _sitem ){2318 var _dt = _p.parseDatatype( _sitem )2319 if( _dt && _p[ _dt ] && _sitem.val() ){2320 if( _p[ _dt ]( _sitem ) ){ 2321 Valid.setValid( _sitem );2322 }2323 }else{2324 Valid.setValid( _sitem );2325 }2326 });2327 !_r && _item.attr( 'datatypestatus', 'false' );2328 !_r && _errLs.length && $.each( _errLs, function( _ix, _sitem ){ 2329 _sitem = $( _sitem );2330 var _sv = ( _sitem.val() || '' ).trim();2331 if( _isReturn ) return false;2332 if( ! _sv ) return;2333 //JC.log('yyyyyyyyyyyyy', _sitem.data('JCValidStatus'), new Date().getTime() );2334 _sv 2335 && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _sitem, 'uniquemsg', true ] );2336 } );2337 return _r;2338 }2339 , datavalid:2340 function( _item ){2341 var _r = true, _p = this;2342 if( !Valid.isFormValid ) return _r;2343 if( !_item.is( '[datavalid]') ) return _r;2344 //JC.log( 'datavalid', new Date().getTime() ); 2345 _r = JC.f.parseBool( _item.attr('datavalid') );2346 if( !_r ){2347 !_r && _item.attr( 'datatypestatus', 'false' );2348 Valid.statusTimeout.error( _item, 2349 setTimeout( function(){2350 $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item, 'datavalidmsg', true ] );2351 }, 1 )2352 );2353 }2354 return _r;2355 }2356 , typeLen:2357 function( _type ){2358 var _lenAr = [1];2359 _type 2360 && ( _type = _type.replace( /[^\d\.]/g, '' ) )2361 && ( _lenAr = _type.split('.') )2362 && ( 2363 _lenAr[0] = parseInt( _lenAr[0], 10 ) || 12364 , _lenAr[1] = parseInt( _lenAr[1], 10 ) || 02365 )2366 ;2367 return _lenAr;2368 }2369 , findValidEle:2370 function( _item ){2371 var _p = this, _selector = '~ em.validmsg', _r = _item.find( _selector ), _tmp;2372 if( _item.attr('validel') 2373 && ( _tmp = _p.getElement( _item.attr('validel'), _item, _selector ) ).length ) _r = _tmp;2374 return _r;2375 }2376 , findFocusEle:2377 function( _item ){2378 var _p = this, _selector = '~ em.focusmsg', _r = _item.find( _selector ), _tmp;2379 if( _item.attr('focusel') 2380 && ( _tmp = _p.getElement( _item.attr('focusel'), _item, _selector ) ).length ) _r = _tmp;2381 return _r;2382 }2383 , findErrorEle:2384 function( _item ){2385 var _p = this, _selector = Model.SELECTOR_ERROR, _r = _item.find( _selector ), _tmp;2386 if( _item.attr('emel') 2387 && ( _tmp = _p.getElement( _item.attr('emel'), _item, _selector ) ).length ) _r = _tmp;2388 return _r;2389 }2390 /**2391 * 获取 _selector 对象2392 * <br />这个方法的存在是为了向后兼容qwrap, qwrap DOM参数都为ID2393 * @param {selector} _selector2394 */2395 , getElement: 2396 function( _selector, _item, _subselector ){2397 if( /^\^$/.test( _selector ) ){2398 _subselector = _subselector || Model.SELECTOR_ERROR;2399 _selector = $( _item.parent().find( _subselector ) );2400 }else if( /^[\/\|\<\(]/.test( _selector ) ) {2401 _selector = JC.f.parentSelector( _item, _selector );2402 }else if( /\./.test( _selector ) ) {2403 return $( _selector );2404 }else if( /^[\w-]+$/.test( _selector ) ) {2405 _selector = '#' + _selector;2406 _selector = $( _selector.replace( /[\#]+/g, '#' ) );2407 }2408 return $(_selector);2409 }2410 /**2411 * 获取对应的错误信息, 默认的错误信息有 reqmsg, errmsg, <br />2412 * 注意: 错误信息第一个字符如果为空格的话, 将完全使用用户定义的错误信息, 将不会动态添加 请上传/选择/填写2413 * @param {selector} _item2414 * @param {string} _msgAttr - 显示指定需要读取的错误信息属性名, 默认为 reqmsg, errmsg, 通过该属性可以指定别的属性名2415 * @param {bool} _fullMsg - 显示指定错误信息为属性的值, 而不是自动添加的 请上传/选择/填写2416 */2417 , errorMsg: 2418 function( _item, _msgAttr, _fullMsg ){2419 var _msg = _item.is('[errmsg]') ? ' ' + _item.attr('errmsg') : _item.is('[reqmsg]') ? _item.attr('reqmsg') : '';2420 _msgAttr && (_msg = _item.attr( _msgAttr ) || _msg );2421 _fullMsg && _msg && ( _msg = ' ' + _msg );2422 _msg = (_msg||'').trim().toLowerCase() == 'undefined' || typeof _msg == undefined ? '' : _msg;2423 if( _msg && !/^[\s]/.test( _msg ) ){2424 switch( _item.prop('type').toLowerCase() ){2425 case 'file': _msg = '请上传' + _msg; break;2426 case 'select-multiple':2427 case 'select-one':2428 case 'checkbox':2429 case 'radio':2430 case 'select': _msg = '请选择' + _msg; break;2431 case 'textarea':2432 case 'password':2433 case 'text': _msg = '请填写' + _msg; break;2434 }2435 }2436 return $.trim(_msg);2437 }2438 /**2439 * 检查内容是否为空,2440 * <br>如果声明了该属性, 那么 value 须不为空2441 * @param {selector} _item2442 * @example2443 <div class="f-l">2444 <input type="TEXT" name="company_name" reqmsg="公司名称" /> <em>公司名称描述</em>2445 </div>2446 */2447 , reqmsg: 2448 function( _item ){2449 var _r = true, _p = this;2450 if( !_p.isReqmsg( _item ) ) return _r;2451 if( _item.val() && _item.val().constructor == Array ){2452 _r = !!( $.trim( _item.val().join('') + '' ) );2453 }else{2454 _r = !!$.trim( _item.val() ||'') ;2455 }2456 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item, 'reqmsg' ] );2457 //JC.log( 'regmsgValid: ' + _r );2458 return _r;2459 }2460 , sametypeitems:2461 function( _item ){2462 var _p = this, _r = []2463 , _pnt = _item.parent()2464 , _type = _item.attr('datatype')2465 , _re = new RegExp( _type, 'i' )2466 ;2467 if( /select/i.test( _item.prop('nodeName') ) ){2468 _pnt.find('[datatype]').each( function(){2469 _re.test( $(this).attr('datatype') ) && _r.push( $(this) );2470 });2471 }else{2472 _pnt.find('input[datatype]').each( function(){2473 _re.test( $(this).attr('datatype') ) && _r.push( $(this) );2474 });2475 }2476 return _r.length ? $( _r ) : _r;2477 }2478 , samesubtypeitems:2479 function( _item, _type ){2480 var _p = this, _r = []2481 , _pnt = _item.parent()2482 , _type = _type || _item.attr('subdatatype')2483 , _re = new RegExp( _type, 'i' )2484 , _nodeName = _item.prop('nodeName').toLowerCase()2485 , _tagName = 'input'2486 ;2487 if( /select/.test( _nodeName ) ){2488 _tagName = 'select';2489 }else if( /textarea/.test( _nodeName ) ){2490 _tagName = 'textarea';2491 }2492 _pnt.find( _tagName + '[subdatatype]').each( function(){2493 _re.test( $(this).attr('subdatatype') ) && _r.push( $(this) );2494 });2495 return _r.length ? $( _r ) : _r;2496 }2497 , focusmsgeverytime:2498 function( _item ){2499 var _r = Valid.focusmsgEverytime;2500 _item.is( '[focusmsgeverytime]' ) && ( _r = JC.f.parseBool( _item.attr('focusmsgeverytime') ) );2501 return _r;2502 }2503 , validemdisplaytype:2504 function( _item ){2505 _item && ( _item = $( _item ) );2506 var _r = Valid.emDisplayType, _form = JC.f.getJqParent( _item, 'form' ), _tmp;2507 _form &&_form.length 2508 && _form.is( '[validemdisplaytype]' ) 2509 && ( _tmp = _form.attr('validemdisplaytype') )2510 && ( _r = _tmp )2511 ;2512 _item.is( '[validemdisplaytype]' ) 2513 && ( _tmp = _item.attr('validemdisplaytype') )2514 && ( _r = _tmp )2515 ;2516 //JC.log( 'validemdisplaytype:', _r, Valid.emDisplayType );2517 return _r;2518 }2519 /**2520 * 这里需要优化检查, 目前会重复检查(2次)2521 * 2522 */2523 , checkedType:2524 function( _item, _type ){2525 _item && ( _item = $( _item ) );2526 _type = _type || 'checkbox';2527 var _p = this2528 , _r = true2529 , _items2530 , _tmp2531 , _ckLen = 12532 , _ckMaxLen = 02533 , _count = 02534 , _finder = _item2535 , _pntIsLabel = _item.parent().prop('nodeName').toLowerCase() == 'label' 2536 , _finderKey = _type + 'finder'2537 , _KEY = 'checkedType_' + _type 2538 , _isReturn2539 ;2540 if( _p.checkRepeatProcess( _item, _KEY, true ) && !_item.data( 'Last' + _type ) ) {2541 return !_item.data( 'isErrorVck' ); 2542 }2543 //JC.log( 'checkedType', JC.f.gid() );2544 if( _item.is( '[datatarget]' ) ){2545 _items = JC.f.parentSelector( _item, _item.attr('datatarget') ); 2546 _tmp = [];2547 _items.each( function(){2548 var _sp = $(this);2549 if( 2550 ( _sp.is(':visible') || _p.isValidHidden( _sp ) )2551 && !_sp.prop('disabled')2552 ){2553 _tmp.push( _sp );2554 if( _p.checkRepeatProcess( _sp, _KEY, true ) ) {2555 _isReturn = true;2556 }2557 }2558 });2559 _items = $( _tmp );2560 }else{2561 if( _pntIsLabel ){2562 if( !_finder.is('[' + _finderKey + ']') ) _finder = _item.parent().parent();2563 else _finder = JC.f.parentSelector( _item, _item.attr( _finderKey ) );2564 _tmp = JC.f.parentSelector( _finder, '|input[datatype]' );2565 }2566 else{2567 _tmp = JC.f.parentSelector( _finder, '/input[datatype]' );2568 }2569 _items = [];2570 _tmp.each( function(){2571 var _sp = $(this);2572 var _re = new RegExp( _type, 'i' );2573 if( 2574 _re.test( _sp.attr('datatype') ) 2575 && ( _sp.is(':visible') || _p.isValidHidden( _sp ) )2576 && !_sp.prop('disabled')2577 ){2578 _items.push( _sp );2579 if( _p.checkRepeatProcess( _sp, _KEY, true ) ) {2580 _isReturn = true;2581 }2582 }2583 });2584 _items = $( _items );2585 }2586 if( _pntIsLabel ){2587 _items.each( function(){2588 var _sp = $(this);2589 if( !_sp.is('[emel]') ) _sp.attr('emel', '//em.error');2590 if( !_sp.is('[validel]') ) _sp.attr('validel', '//em.validmsg');2591 if( !_sp.is('[focusel]') ) _sp.attr('focusel', '//em.focusmsg');2592 });2593 }2594 _items.length && $( _item = _items[ _items.length - 1 ] ).data('Last' + _type, true);2595 if( _items.length ){2596 if( _item.is( '[datatype]' ) && _item.attr( 'datatype' ) ){2597 _item.attr('datatype').replace( /[^\-]+?\-([\d]+)/, function( $0, $1 ){ _ckLen = parseInt( $1, 10 ) || _ckLen; } );2598 _item.attr('datatype').replace( /[^\-]+?\-[\d]+?(?:\.|\-)([\d]+)/, function( $0, $1 ){ _ckMaxLen = parseInt( $1, 10 ) || _ckMaxLen; } );2599 }2600 if( _items.length >= _ckLen ){2601 _items.each( function(){2602 $( this ).prop( 'checked' ) && _count++;2603 });2604 if( _count < _ckLen ){2605 _r = false;2606 }else if( _ckMaxLen && _count > _ckMaxLen ){2607 _r = false;2608 }2609 }2610 if( !_r ){2611 _item.data( 'isErrorVck', true );2612 _items.each( function(){2613 $( this ).data( 'isErrorVck', true );2614 });2615 }else{2616 _item.data( 'isErrorVck', false );2617 _items.each( function(){2618 $( this ).data( 'isErrorVck', false );2619 });2620 }2621 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );2622 }2623 return _r;2624 }2625 , 'checkbox':2626 function( _item ){2627 return this.checkedType( _item, 'checkbox' );2628 }2629 , 'radio':2630 function( _item ){2631 return this.checkedType( _item, 'radio' );2632 }2633 /**2634 * 验证文件扩展名2635 */2636 , 'file':2637 function( _item ){2638 var _p = this2639 , _r = true2640 , _v = _item.val().trim().toLowerCase()2641 , _extLs = _p.dataFileExt( _item )2642 , _re2643 , _tmp2644 ;2645 if( _extLs.length ){2646 _r = false;2647 $.each( _extLs, function( _ix, _item ){2648 _item += '$';2649 _re = new RegExp( _item, 'i' );2650 if( _re.test( _v ) ) {2651 _r = true;2652 return false;2653 }2654 });2655 }2656 !_r && $(_p).trigger( Model.TRIGGER, [ Model.ERROR, _item ] );2657 return _r;2658 }2659 , dataFileExt:2660 function( _item ){2661 var _r = [], _tmp;2662 _item.is('[fileext]')2663 && ( _tmp = _item.attr('fileext').replace(/[\s]+/g, '' ) )2664 && ( _tmp = _tmp.replace( /\./g, '\\.' ) )2665 && ( _r = _tmp.toLowerCase().split(',') )2666 ;2667 return _r;2668 }2669 , ignoreAutoCheckEvent:2670 function( _item ){2671 var _r = Valid.ignoreAutoCheckEvent, _form;2672 _item && ( _item = $( _item ) );2673 if( _item && _item.length ){2674 _form = JC.f.getJqParent( _item, 'form' );2675 _form 2676 && _form.length 2677 && _form.is( '[ignoreAutoCheckEvent]' )2678 && ( _r = JC.f.parseBool( _form.attr( 'ignoreAutoCheckEvent' ) ) );2679 2680 _item.is( '[ignoreAutoCheckEvent]' )2681 && ( _r = JC.f.parseBool( _item.attr( 'ignoreAutoCheckEvent' ) ) );2682 }2683 return _r;2684 }2685 };2686 2687 function View( _model ){2688 this._model = _model;2689 }2690 2691 View.prototype = {2692 init:2693 function() {2694 var _p = this;2695 2696 $(_p).on( 'setValid', function( _evt, _item, _tm, _noStyle, _hideFocusMsg ){2697 var _tmp;2698 _item.removeClass( Model.CSS_ERROR );2699 _item.find( 2700 JC.f.printf( '~ em:not("em.focusmsg, em.validmsg, {0}")', Model.FILTER_ERROR ) )2701 .css('display', _p._model.validemdisplaytype( _item ) 2702 );2703 _item.find( Model.SELECTOR_ERROR ).hide();2704 _item.attr('emel') 2705 && ( _tmp = _p._model.getElement( _item.attr('emel'), _item ) )2706 && _tmp.hide();2707 typeof _noStyle == 'undefined' 2708 && typeof _item.val() != 'object'2709 && !_item.val().trim() 2710 && ( _noStyle = 1 );2711 _p.validMsg( _item, _noStyle, _hideFocusMsg );2712 });2713 $( _p ).on( 'setError', function( _evt, _item, _msgAttr, _fullMsg ){2714 var _msg = _p._model.errorMsg.apply( _p._model, [ _item, _msgAttr, _fullMsg ] )2715 , _errEm2716 , _validEm2717 , _focusEm2718 , _tmp2719 ;2720 _item.addClass( Model.CSS_ERROR );2721 _item.find( JC.f.printf( '~ em:not({0})', Model.FILTER_ERROR ) ).hide();2722 if( _item.is( '[validel]' ) ){2723 ( _validEm = _p._model.getElement( _item.attr( 'validel' ) , _item) ) 2724 && _validEm.hide();2725 }2726 if( _item.is( '[focusel]' ) ){2727 ( _focusEm = _p._model.getElement( _item.attr( 'focusel' ) , _item) ) 2728 && _focusEm.hide();2729 }2730 if( _item.is( '[emEl]' ) ){2731 ( _errEm = _p._model.getElement( _item.attr( 'emEl' ) , _item) ) 2732 && _errEm.addClass( Model.CSS_ERROR );2733 }2734 !( _errEm && _errEm.length ) && ( _errEm = _item.find( Model.SELECTOR_ERROR ) );2735 if( !_errEm.length ){2736 ( _errEm = $( JC.f.printf( '<em class="{0}"></em>', Model.CSS_ERROR ) ) ).insertAfter( _item );2737 }2738 !_msg.trim() && ( _msg = "&nbsp;" );2739 _errEm.html( _msg ).css('display', _p._model.validemdisplaytype( _item ) );2740 //JC.log( 'error:', _msg );2741 });2742 return this;2743 }2744 /**2745 * 显示正确的视觉效果2746 * @param {selector} _item2747 * @param {int} _tm2748 * @param {bool} _noStyle2749 */2750 , valid:2751 function( _item, _tm, _noStyle ){2752 _item && ( _item = $(_item) );2753 var _p = this, _tmp;2754 _item.data( 'JCValidStatus', true );2755 //if( !_p._model.isValid( _item ) ) return false;2756 var _hideFocusMsg = !JC.f.parseBool( _item.attr('validnoerror' ) );2757 Valid.statusTimeout.valid( _item,2758 setTimeout(function(){2759 $(_p).trigger( 'setValid', [ _item, _tm, _noStyle, _hideFocusMsg ] );2760 ( _tmp = _p._model.validitemcallback( _item ) ) && _tmp( _item, true );2761 }, _tm || 150)2762 );2763 }2764 , validMsg:2765 function( _item, _noStyle, _hideFocusMsg ){2766 var _p = this, _msg = ( _item.attr('validmsg') || '' ).trim().toLowerCase(), _focusEm;2767 if( _p._model.isValidMsg( _item ) ){2768 if( _msg == 'true' || _msg == '1' ) _msg = '';2769 !_msg.trim() && ( _msg = '&nbsp;' ); //chrome bug, 内容为空会换行2770 var _focusmsgem = _p._model.findFocusEle( _item )2771 , _validmsgem = _p._model.findValidEle( _item )2772 , _errorEm = _p._model.findErrorEle( _item )2773 ;2774 !_validmsgem.length 2775 && ( _validmsgem = $( '<em class="validmsg"></em>' )2776 , _item.after( _validmsgem )2777 );2778 //_focusmsgem && _focusmsgem.length && _focusmsgem.hide();2779 _validmsgem.html( _msg );2780 _noStyle 2781 ? _validmsgem.hide() 2782 : ( _validmsgem.css('display', _p._model.validemdisplaytype( _item ) )2783 , _focusmsgem && _focusmsgem.hide()2784 , _errorEm && _errorEm.hide()2785 )2786 ;2787 }else{2788 if( _hideFocusMsg ){2789 ( _focusEm = _p._model.findFocusEle( _item ) ) 2790 && _focusEm.hide();2791 }2792 }2793 }2794 /**2795 * 显示错误的视觉效果2796 * @param {selector} _item2797 * @param {string} _msgAttr - 显示指定需要读取的错误信息属性名, 默认为 reqmsg, errmsg, 通过该属性可以指定别的属性名2798 * @param {bool} _fullMsg - 显示指定错误信息为属性的值, 而不是自动添加的 请上传/选择/填写2799 */2800 , error: 2801 function( _item, _msgAttr, _fullMsg ){2802 _item && ( _item = $(_item) );2803 var _p = this, arg = arguments, _tmp; 2804 //if( !_p._model.isValid( _item ) ) return true;2805 if( _item.is( '[validnoerror]' ) ) return true;2806 _item.data( 'JCValidStatus', false );2807 Valid.statusTimeout.error( _item, 2808 setTimeout(function(){2809 $(_p).trigger( 'setError', [ _item, _msgAttr, _fullMsg ] );2810 ( _tmp = _p._model.validitemcallback( _item ) ) && _tmp( _item, false);2811 }, 150)2812 );2813 return false;2814 }2815 , focusmsg:2816 function( _item, _setHide, _msgAttr ){2817 //alert( _msgAttr );2818 if( _item && ( _item = $( _item ) ).length 2819 && ( _item.is('[focusmsg]') || ( _msgAttr && _item.is( '[' + _msgAttr + ']') ) )2820 ){2821 //JC.log( 'focusmsg', new Date().getTime() );2822 var _r, _p = this2823 , _focusmsgem = _p._model.findFocusEle( _item )2824 , _validmsgem = _p._model.findValidEle( _item )2825 , _errorEm = _p._model.findErrorEle( _item )2826 , _msg = _item.attr('focusmsg')2827 ;2828 _msgAttr && ( _msg = _item.attr( _msgAttr || _msg ) );2829 if( _setHide && _focusmsgem && _focusmsgem.length ){2830 _focusmsgem.hide();2831 return;2832 }2833 _errorEm.length && _errorEm.is(':visible') && _errorEm.hide();2834 if( _validmsgem.length && _validmsgem.is(':visible') ) return;2835 !_focusmsgem.length 2836 && ( _focusmsgem = $('<em class="focusmsg"></em>')2837 , _item.after( _focusmsgem )2838 );2839 if( _item.is( '[validnoerror]' ) ){2840 _r = Valid.check( _item );2841 }else{2842 _item.attr('validnoerror', true);2843 _r = Valid.check( _item );2844 _item.removeAttr('validnoerror');2845 }2846 !_msg.trim() && ( _msg = "&nbsp;" );2847 if( _p._model.focusmsgeverytime( _item ) ){2848 _focusmsgem.html( _msg ).css('display', _p._model.validemdisplaytype( _item ) );2849 }else{2850 _r && _focusmsgem.html( _msg ).css('display', _p._model.validemdisplaytype( _item ) );2851 }2852 }2853 }2854 };2855 /**2856 * 解析错误时触发的时件2857 * @event ValidError2858 */2859 /**2860 * 解析正确时触发的时件2861 * @event ValidCorrect2862 */2863 /**2864 * 响应表单子对象的 blur事件, 触发事件时, 检查并显示错误或正确的视觉效果2865 * @private2866 */2867 $(document).delegate( 'input[type=text], input[type=password], textarea', 'blur', function($evt){2868 var _p = $(this), _ins = Valid.getInstance();2869 if( _ins._model.ignoreAutoCheckEvent( _p ) ) return;2870 _ins.trigger( Model.FOCUS_MSG, [ _p, true ] );2871 Valid.checkTimeout( _p );2872 });2873 /**2874 * 响应没有 type 的 文本框2875 */2876 $(document).delegate( 'input', 'blur', function( _evt ){2877 var _p = $(this), _ins = Valid.getInstance();2878 if( _p.attr( 'type' ) ) return;2879 if( _ins._model.ignoreAutoCheckEvent( _p ) ) return;2880 _ins.trigger( Model.FOCUS_MSG, [ _p, true ] );2881 Valid.checkTimeout( _p );2882 });2883 $(document).delegate( 'input', 'focus', function($evt){2884 var _p = $(this), _ins = Valid.getInstance(), _v = ( _p.val()||'').trim();2885 if( _p.attr( 'type' ) ) return;2886 if( _ins._model.ignoreAutoCheckEvent( _p ) ) return;2887 _ins.trigger( Model.FOCUS_MSG, [ _p ] );2888 !_v && Valid.setValid( _p );2889 });2890 /**2891 * 响应表单子对象的 change 事件, 触发事件时, 检查并显示错误或正确的视觉效果2892 * @private2893 */2894 $(document).delegate( 'select, input[type=file], input[type=checkbox], input[type=radio]', 'change', function($evt, _ignore){2895 if( _ignore ) return;2896 var _p = $(this), _ins = Valid.getInstance();2897 if( _ins._model.ignoreAutoCheckEvent( _p ) ) return;2898 Valid.checkTimeout( _p );2899 });2900 /**2901 * 响应表单子对象的 focus 事件, 触发事件时, 如果有 focusmsg 属性, 则显示对应的提示信息2902 * @private2903 */2904 $(document).delegate( 'input[type=text], input[type=password], textarea'2905 +', select, input[type=file], input[type=checkbox], input[type=radio]', 'focus', function($evt){2906 var _p = $(this), _ins = Valid.getInstance(), _v = ( _p.val() || '' ).trim();2907 if( _ins._model.ignoreAutoCheckEvent( _p ) ) return;2908 _ins.trigger( Model.FOCUS_MSG, [ _p ] );2909 !_v && Valid.setValid( _p );2910 });2911 /**2912 * 响应表单子对象的 blur事件, 触发事件时, 如果有 focusmsg 属性, 则显示对应的提示信息2913 * @private2914 */2915 $(document).delegate( 'select, input[type=file], input[type=checkbox], input[type=radio]', 'blur', function($evt){2916 var _p = $(this), _ins = Valid.getInstance();2917 if( _ins._model.ignoreAutoCheckEvent( _p ) ) return;2918 _ins.trigger( Model.FOCUS_MSG, [ _p, true ] );2919 });2920 $(document).delegate( 'input[type=hidden][subdatatype]', 'change', function( _evt ){2921 var _p = $(this), _ins = Valid.getInstance(), _isHidden = false, _tmp;2922 if( _ins._model.ignoreAutoCheckEvent( _p ) ) return;2923 _p.is( '[subdatatype]' ) && ( _isHidden = /hidden/i.test( _p.attr('subdatatype') ) );2924 if( _p.data('HID_CHANGE_CHECK') ){2925 _tmp = new Date().getTime() - _p.data('HID_CHANGE_CHECK') ;2926 if( _tmp < 50 ){2927 return;2928 }2929 }2930 if( !_p.val() ){2931 //Valid.setValid( _p );2932 return;2933 }2934 _p.data('HID_CHANGE_CHECK', new Date().getTime() );2935 //JC.log( 'hidden val', new Date().getTime(), _p.val() );2936 Valid.checkTimeout( $(this) );2937 });2938 /**2939 * 初始化 [ subdatatype = datavalid | exdatatype = datavalid ] 相关事件2940 */2941 $(document).delegate( 'input[type=text][subdatatype], input[type=text][exdatatype]', 'keyup', function( _evt ){2942 var _sp = $(this), _isEx;2943 var _isDatavalid = /datavalid/i.test( _sp.attr('exdatatype') || _sp.attr('subdatatype') );2944 if( !_isDatavalid ) return;2945 if( _sp.prop('disabled') || _sp.prop('readonly') ) return;2946 _sp.attr( 'exdatatype' ) && ( _isEx = true );2947 Valid.dataValid( _sp, false, true );2948 var _keyUpCb;2949 _sp.attr('datavalidKeyupCallback')2950 && ( _keyUpCb = window[ _sp.attr('datavalidKeyupCallback') ] )2951 && _keyUpCb.call( _sp, _evt )2952 ;2953 if( _sp.data( 'DataValidInited' ) ) return;2954 _sp.data( 'DataValidInited', true );2955 _sp.data( 'DataValidCache', {} );2956 !_sp.is( '[datavalidNoCache]' ) && _sp.attr( 'datavalidNoCache', true );2957 //JC.log( JC.f.parseBool( _sp.attr( 'datavalidNoCache' ) ) );2958 _sp.on( 'DataValidUpdate', function( _evt, _v, _data ){2959 var _tmp, _json;2960 if( JC.f.parseBool( _sp.attr( 'datavalidNoCache' ) ) ){2961 _json = _data;2962 }else{2963 if( !_sp.data( 'DataValidCache') ) return;2964 _json = _sp.data( 'DataValidCache' )[ _v ];2965 }2966 if( !_json ) return;2967 _v === 'suchestest' && ( _json.data.errorno = 0 );2968 Valid.dataValid( _sp, !_json.data.errorno, false, _json.data.errmsg );2969 _sp.attr('datavalidCallback')2970 && ( _tmp = window[ _sp.attr('datavalidCallback') ] )2971 && _tmp.call( _sp, _json.data, _json.text )2972 ;2973 });2974 _sp.on( 'DataValidVerify', function( _evt, _ignoreStatus, _cb ){2975 var _v = _sp.val().trim(), _tmp, _strData2976 , _url = _sp.attr('datavalidurl')2977 , _datavalidCheckCallback;2978 if( !_v ) return;2979 _sp.attr('datavalidCheckCallback')2980 && ( _datavalidCheckCallback = window[ _sp.attr('datavalidCheckCallback') ] )2981 ;2982 if( _datavalidCheckCallback ){2983 innerDone( _datavalidCheckCallback.call( _sp ) );2984 return;2985 }2986 if( !_url ) return;2987 _sp.data( 'DataValidTm' ) && clearTimeout( _sp.data( 'DataValidTm') );2988 _sp.data( 'DataValidTm'2989 , setTimeout( function(){2990 _v = _sp.val().trim();2991 if( !_v ) return;2992 _v = JC.f.encoder( _sp )( _v );2993 if( !_ignoreStatus ){2994 if( !_sp.data('JCValidStatus') ) return;2995 }2996 _url = JC.f.printf( _url, _v );2997 _sp.attr('datavalidUrlFilter')2998 && ( _tmp = window[ _sp.attr('datavalidUrlFilter') ] )2999 && ( _url = _tmp.call( _sp, _url ) )3000 ;3001 if( _v in _sp.data( 'DataValidCache' ) ){3002 _sp.trigger( 'DataValidUpdate', _v );3003 return;3004 }3005 var _ajaxType = 'get', _requestData;3006 _sp.attr( 'datavalidAjaxType' ) && ( _ajaxType = _sp.attr( 'datavalidAjaxType' ) || _ajaxType );3007 if( _sp.attr( 'datavalidRequestData' ) ){3008 try{ _requestData = eval( '(' + _sp.attr('datavalidRequestData') + ')' ); }catch( ex ){}3009 }3010 _requestData = _requestData || {};3011 if( _ajaxType.toLowerCase() == 'post' ){3012 $.post( _url, _requestData ).done( innerDone );3013 }else{3014 $.get( _url, _requestData ).done( innerDone );3015 }3016 }, 151)3017 );3018 function innerDone( _d ){3019 _strData = _d;3020 if( typeof _d == 'string' ){3021 try{ _d = $.parseJSON( _d ); } catch( ex ){ _d = { errorno: 1 }; }3022 }3023 var _data = { 'key': _v, data: _d, 'text': _strData };3024 !JC.f.parseBool( _sp.attr( 'datavalidNoCache' ) )3025 && ( _sp.data( 'DataValidCache' )[ _v ] = _data );3026 _sp.trigger( 'DataValidUpdate', [ _v, _data ] );3027 _cb && _cb.call( _sp, _data );3028 }3029 });3030 _sp.on( 'blur', function( _evt, _ignoreProcess ){3031 //JC.log( 'datavalid', new Date().getTime() );3032 if( _ignoreProcess ) return;3033 _sp.trigger( 'DataValidVerify' );3034 });3035 });3036 return JC.Valid;3037});}( typeof define === 'function' && define.amd ? define : 3038 function ( _name, _require, _cb) { 3039 typeof _name == 'function' && ( _cb = _name );3040 typeof _require == 'function' && ( _cb = _require ); 3041 _cb && _cb(); 3042 }3043 , window3044 )...

Full Screen

Full Screen

FlowChart.js

Source:FlowChart.js Github

copy

Full Screen

1/**2 * 支持 多对多 关系( 目前只支持 一对多 和 多对一 )3 */4 ;(function(define, _win) { 'use strict'; define( 'JC.FlowChart', [ 'Raphael', 'JC.BaseMVC', 'JC.PopTips' ], function(){5/**6 * <dl>7 * <dt>JC 流程图</dt>8 * <dd style="">一对多关系</dd>9 * <dd>多对一关系</dd>10 * <dd style="color:#ccc;text-decoration: line-through;">多对多关系</dd>11 * </dl>12 * <p><b>require</b>:13 * <a href='window.Raphael.html'>RaphaelJS</a>14 * , <a href='JC.BaseMVC.html'>JC.BaseMVC</a>15 * , <a href='JC.PopTips.html'>JC.PopTips</a>16 * </p>17 *18 * <p><a href='https://github.com/openjavascript/jquerycomps' target='_blank'>JC Project Site</a>19 * | <a href='http://jc2.openjavascript.org/docs_api/classes/JC.FlowChart.html' target='_blank'>API docs</a>20 * | <a href='../../modules/JC.FlowChart/0.1/_demo' target='_blank'>demo link</a></p>21 * 22 * <h2>页面只要引用本脚本, 默认会处理 div class="js_compFlowChart"</h2>23 *24 * <h2>可用的 HTML attribute</h2>25 *26 * <dl>27 * <dt>data-FlowChart = script json data</dt>28 * <dd>流程图数据29 * <dl>30 * <dt>数据说明</dt>31 * <dd>数据按节点关系分为两大类: 一对多, 多对一</dd>32 * <dd>33 * <dl>34 * <dt>一对多数据</dt>35 * <dd>一对多数据存放于字段: nodes, nodes 数据类型为数组</dd>36 * <dd>nodes 字段位于数据节点里</dd>37 * </dl>38 * <dl>39 * <dt>多对一数据</dt>40 * <dd>多对一数据存放于字段: targetNodes, targetNodes 数据类型为对象</dd>41 * <dd>targetNodes 字段为全局节点</dd>42 * </dl>43 * </dd>44 * </dl>45 * <dl>46 * <dt>数据字段说明</dt>47 * <dd>48 * <h2>图表数据 - chart 字段</h2>49 * <dl>50 * <dt>name = string</dt>51 * <dd>节点名</dd>52 *53 * <dt>id = string</dt>54 * <dd>节点唯一标识符</dd>55 *56 * <dt>nodes = array</dt>57 * <dd>一对多数据的子节点, 该字段位于父节点里面</dd>58 *59 * <dt>targetNodes = object</dt>60 * <dd>多对一数据的子节点, 该字段为全局字段, 节点位置 chart.targetNodes</dd>61 *62 * <dt>status = string, default = 0</dt>63 * <dd>64 * 节点状态65 * <br/>根据 status 显示为不同的样式66 * <br/>默认有0 ~ 10, 共11 种状态67 * <br/>由status 产生的 css class: js_cfcItemStatus_N, js_cfcItemTips_N ( N 代表 status )68 * </dd>69 *70 * <dt>tipsHtml = string</dt>71 * <dd>鼠标划过节点时, 显示的tips内容, 支持html内容</dd>72 * </dl>73 * <h2>线条与图标颜色 - colors 字段</h2>74 * <dl>75 * <dt>line = raphael object, default: { 'stroke': '#E1E1E1', 'stroke-width': 2 } </dt>76 * <dd>背景线颜色</dd>77 *78 * <dt>icon = raphael object, default: { 'stroke': '#E1E1E1', 'stroke-width': 2, 'fill': '#F2F2F2' } </dt>79 * <dd>图标颜色</dd>80 *81 * <dt>如果要自定义节点颜色 或者 tips 颜色, 请使用 css 定义: js_cfcItemStatus_N, js_cfcItemTips_N ( N 代表 status ) </dt>82 * </dl>83 * </dd>84 * </dl>85 * <dd>86 * </dl> 87 *88 * @namespace JC89 * @class FlowChart90 * @extends JC.BaseMVC91 * @constructor92 * @param {selector|string} _selector 93 * @version dev 0.1 2014-09-0394 * @author qiushaowei <suches@btbtd.org> | 75 Team95 * @example96<pre>97 &lt;div class="js_compFlowChart" data-FlowChart="|script">98 &lt;script type="text/template">99 {100 chart: {101 name: '提交'102 , id: 1103 , nodes: [104 {105 name: '资质审核'106 , id: 2107 , status: 1108 , tipsHtml: 'username 1'109 , nodes: [110 {111 name: '服务审核'112 , id: 3113 , targetNode: 5114 , status: 2115 , tipsHtml: 'username 2'116 }117 , {118 name: '渠道管理层'119 , id: 4120 , status: 3121 , tipsHtml: 'username 3'122 }123 ]124 }125 , {126 name: '资质审核1'127 , id: 6128 , status: 4129 , tipsHtml: 'username 4'130 , nodes: [131 {132 name: '服务审核1'133 , id: 7134 , targetNode: 9135 , status: 5136 , tipsHtml: 'username 5'137 }138 , {139 name: '渠道管理层1'140 , id: 8141 , targetNode: 9142 , status: 6143 , tipsHtml: 'username 6'144 }145 ]146 }147 , {148 name: '资质审核2'149 , id: 10150 , status: 7151 , tipsHtml: 'username 7'152 , nodes: [153 {154 name: '服务审核2'155 , id: 11156 , status: 8157 , tipsHtml: 'username 8'158 , nodes: [159 {160 name: '管理层2'161 , id: 12162 , targetNode: 5163 , status: 9164 , tipsHtml: 'username 9'165 }166 ]167 }168 ]169 }170 , {171 name: '资质审核3'172 , id: 15173 , status: 10174 , tipsHtml: 'username 10'175 }176 ]177 , targetNodes: {178 '5': {179 name: '管理层'180 }181 , '9': {182 name: '管理层1'183 , targetNode: 5184 }185 }186 }187 }188 &lt;/script>189 &lt;/div>190</pre>191 */192 var _jdoc = $( document ), _jwin = $( window );193 var isIE = !!window.ActiveXObject;194 JC.FlowChart = FlowChart;195 if( JC.use ){196 !window.Raphael && ( JC.use( 'plugins.raphael' ) );197 !JC.PopTips && ( JC.use( 'JC.PopTips' ) );198 }199 function FlowChart( _selector ){200 _selector && ( _selector = $( _selector ) );201 if( JC.BaseMVC.getInstance( _selector, FlowChart ) ) 202 return JC.BaseMVC.getInstance( _selector, FlowChart );203 JC.BaseMVC.getInstance( _selector, FlowChart, this );204 this._model = new FlowChart.Model( _selector );205 this._view = new FlowChart.View( this._model );206 this._init();207 //JC.log( FlowChart.Model._instanceName, 'all inited', new Date().getTime() );208 }209 /**210 * 初始化可识别的 FlowChart 实例211 * @method init212 * @param {selector} _selector213 * @static214 * @return {Array of FlowChartInstance}215 */216 FlowChart.init =217 function( _selector ){218 var _r = [];219 _selector = $( _selector || document );220 if( _selector.length ){221 if( _selector.hasClass( 'js_compFlowChart' ) ){222 _r.push( new FlowChart( _selector ) );223 }else{224 _selector.find( 'div.js_compFlowChart' ).each( function(){225 _r.push( new FlowChart( this ) );226 });227 }228 }229 return _r;230 };231 JC.BaseMVC.build( FlowChart );232 JC.f.extendObject( FlowChart.prototype, {233 _beforeInit:234 function(){235 //JC.log( 'FlowChart _beforeInit', new Date().getTime() );236 }237 , _initHanlderEvent:238 function(){239 var _p = this;240 _p.on( 'inited', function(){241 if( !_p._model.chartData() ) return;242 _p._view.draw();243 _p.notification( JC.FlowChart.Model.INITED, [ _p, _p._model.data() ] );244 });245 //JC.dir( _p._model.chartData() );246 }247 , _inited:248 function(){249 //JC.log( 'FlowChart _inited', new Date().getTime() );250 this.trigger( 'inited' );251 }252 });253 FlowChart.Model._instanceName = 'JCFlowChart';254 /**255 * 初始化后 selector 触发的事件256 * @event cfc_inited257 * @example258<pre>259$( document ).delegate( 260 'div.js_compFlowChart'261 , JC.FlowChart&#46;Model.INITED262 , function( _evt, _ins, _chartData ){263 JC.log( 'js_compFlowChart inited' );264 }265);266</pre>267 */268 FlowChart.Model.INITED = 'cfc_inited'269 /**270 * dom 节点初始化后 触发的事件271 * @event cfc_nodeInited272 * @example273<pre>274$( document ).delegate( 275 'div.js_compFlowChart'276 , JC.FlowChart&#46;Model.ITEM_INITED277 , function( _evt, _domNode, _itemData, _listData, _chartData ){278 JC.log( _domNode.prop( 'nodeName' ) );279 }280);281</pre>282 */283 FlowChart.Model.ITEM_INITED = 'cfc_nodeInited'284 /**285 * dom节点初始化前的事件286 * <br />节点如果有特殊显示需求的话, 可以从这个事件进行相关操作287 * @event cfc_beforeInitItem288 * @example289<pre>290$( document ).delegate( 291 'div.js_compFlowChart'292 , JC.FlowChart&#46;Model.BEFORE_INIT_ITEM293 , function( _evt, _itemData, _listData, _chartData ){294 if( _itemData.tipsHtml ){295 _itemData.tipsHtml += ' <b>test</b>';296 }297 _itemData.name = JC.f.printf( '~{0}~', _itemData.name );298 }299);300</pre>301 */302 FlowChart.Model.BEFORE_INIT_ITEM = 'cfc_beforeInitItem'303 JC.f.extendObject( FlowChart.Model.prototype, {304 init:305 function(){306 //JC.log( 'FlowChart.Model.init:', new Date().getTime() );307 }308 , data:309 function(){310 if( typeof this._data == 'undefined' && this.is( '[data-FlowChart]' ) ){311 //JC.log( this.scriptTplProp( 'data-FlowChart' ) );312 this._data = eval( '(' + this.scriptTplProp( 'data-FlowChart' ) + ')' );313 }314 return this._data;315 }316 , chartData:317 function(){318 return this.data().chart;319 }320 , colorsData:321 function(){322 return this.data().colors;323 }324 , initGrid:325 function(){326 var _p = this;327 _p._grid = { 328 data: []329 , idColumnIndex: {}330 , idColumnIndexList: []331 , row: {}332 , idMap: {}333 , columnIndexMap: {}334 , maxColumn: 0335 , rowIndexPad: 0336 , offsetRowIndex: 10000 337 };338 _p.initIdColumnIndex( _p.chartData(), _p.chartData().id, 0, 0, 0 );339 _p.initColumnIndexMap();340 _p.initColumnRelationship();341 _p.fixLastColumn();342 _p.initColumnRelationship();343 _p.initRowIndex();344 _p.fixNodesRowIndex();345 _p.fixTargetNodesRowIndex();346 /*347 */348 _p.fixRealRowIndex();349 _p.fixFirstLastRowIndex();350 _p.createItems();351 _p.calcRealPosition();352 //JC.dir( _p.gridIdColumnIndex() );353 JC.dir( _p.gridIdColumnIndexMap() );354 //JC.log( _p.gridMaxColumn() );355 }356 , fixLastColumn:357 function(){358 var _p = this359 , _max = _p.gridMaxColumn()360 , _list361 ;362 if( _max < 1 ) return;363 _list = _p.gridIdColumnIndexMap()[ _max ];364 if( _list.length < 2 ) return;365 for( var i = _list.length - 1; i >= 0; i-- ){366 var _item = _list[i];367 if( !( _item.nodes && _item.nodes.length ) && ( _item.pid && _item.pid.length > 1 ) ){368 _list.splice( i, 1 );369 _item.columnIndex = _max + 1;370 _p.gridMaxColumn( _item.columnIndex );371 _p.gridIdColumnIndexMap()[ _p.gridMaxColumn() ] = [ _item ];372 break;373 }374 }375 }376 , grid: function(){ return this._grid; }377 , gridIdColumnIndex: function(){ return this.grid().idColumnIndex; }378 , gridIdColumnIndexList: function(){ return this.grid().idColumnIndexList; }379 , gridIdColumnIndexMap: function(){ return this.grid().columnIndexMap; }380 , gridRow: function(){ return this.grid().row; }381 , gridIdMap: 382 function( _id ){ 383 if( typeof _id != 'undefined' ){384 return this.grid().idMap[ _id ];385 }386 return this.grid().idMap; 387 }388 , gridOffsetRowIndex: function(){ return this.grid().offsetRowIndex; }389 , gridHeight: function(){ return 40; }390 , gridWidth: function(){ return 120; }391 , lineWidth: function(){ return 75; }392 , childLineWidth: function(){ return 40; }393 , parentLineWidth: function(){ return 25; }394 , itemHtmlPattern:395 function( _item ){396 var _r = '{0}';397 ( 'tipsHtml' in _item )398 && _item.tipsHtml399 && ( _r = this.tipsTpl() );400 return _r;401 }402 , tipsTpl:403 function(){404 if( !this._tipsTpl ){405 this._tipsTpl = FlowChart.TIPS_TPL;406 this._tipsTpl = this.scriptTplProp( 'cfcTipsTpl' ) || this._tipsTpl;407 }408 return this._tipsTpl;409 }410 , createItems:411 function(){412 var _p = this, _sx = 0, _sy = 0;413 _p._items = {};414 _p._columnWidth = [];415 for( var i = 0; i <= _p.gridMaxColumn(); i++ ){416 var _rowList = _p.gridIdColumnIndexMap()[ i ]417 , _maxWidth = _p.gridWidth()418 ;419 $.each( _rowList, function( _k, _item ){420 var _html, _itemHtmlPatter421 ;422 423 _p.notification( JC.FlowChart.Model.BEFORE_INIT_ITEM, [ _item, _rowList, _p.data() ] );424 _html = JC.f.printf( 425 '<div class=" ">{0}</div>'426 , _item.name427 , _p.getStatus( _item )428 );429 _itemHtmlPatter = JC.f.printf( _p.itemHtmlPattern( _item ), _html, _item.tipsHtml, _p.getStatus( _item ) );430 var _node = $( _itemHtmlPatter )431 , _tmpWidth432 ;433 _node.addClass( JC.f.printf( 'js_cfcItem js_cfcItemStatus_{0}', _p.getStatus( _item ) ) );434 _node.css( { 'position': 'absolute' } );435 _node.appendTo( _p.box() );436 _node.data( 'nodeData', _item );437 _p._items[ _item.id ] = _node;438 _tmpWidth = _node.width();439 _tmpWidth > _maxWidth && ( _maxWidth = _tmpWidth );440 });441 if( i === 0 ){442 _maxWidth = Math.ceil( _p._items[ _p.chartData().id ].width() + 30 );443 }444 _p._columnWidth.push( _maxWidth );445 }446 }447 , getStatus:448 function( _itemData ){449 var _r = 0;450 ( 'status' in _itemData ) && ( _r = _itemData.status );451 return _r;452 }453 , calcRealPosition:454 function(){455 var _p = this, _sx = 0, _sy = 0, _countX = 0;456 _p._columnX = [];457 _p._minX = _sx;458 _p._maxX = 0;459 _p._minY = 0;460 _p._maxY = 0;461 for( var i = 0; i <= _p.gridMaxColumn(); i++ ){462 var _rowList = _p.gridIdColumnIndexMap()[ i ]463 ;464 $.each( _rowList, function( _k, _item ){465 var _x = _sx, _y = _sy466 ;467 _x += _countX;468 _y += _item.rowIndex * _p.gridHeight();469 _y < _p._minY && ( _p._minY = _y );470 ( _y + _p.gridHeight() / 2 ) > _p._maxY && ( _p._maxY = ( _y + _p.gridHeight() / 2 ) );471 _item.x = _x;472 _item.y = _y;473 //JC.log( i, _item.name, _x, _y, _item.rowIndex );474 });475 _p._maxX = _sx + _countX + _p.columnWidth( i );476 _p._columnX.push( _sx + _countX );477 _countX += Math.max( _p.gridWidth(), _p.columnWidth( i ) ) + _p.lineWidth();478 if( _p.listHasChildline( _rowList ) ){479 _countX += _p.childLineWidth();480 }481 if( _p.listHasParentline( _rowList ) ){482 _countX += _p.parentLineWidth();483 }484 }485 //JC.log( _p._minX, _p._maxX, _p._minY, _p._maxY );486 //JC.log( _p._minY, _p._maxY )487 }488 , minX: function(){ return this._minX; }489 , minY: function(){ return this._minY; }490 , maxX: function(){ return this._maxX; }491 , maxY: function(){ return this._maxY; }492 , items: function(){ return this._items; }493 , item: 494 function( _id ){ 495 return this._items[ _id ]; 496 }497 , columnWidth: 498 function( _ix ){499 if( typeof _ix != undefined ){500 return this._columnWidth[ _ix ] || 0;501 }502 return this._columnWidth;503 }504 , columnX: 505 function( _ix ){506 if( typeof _ix != undefined ){507 return this._columnX[ _ix ] || 0;508 }509 return this._columnX;510 }511 , fixFirstLastRowIndex:512 function(){513 var _p = this;514 _p._maxRowY = 0;515 if( _p.gridMaxColumn() < 2 ) return;516 for( var i = 0; i < _p.gridMaxColumn(); i++ ){517 var _rowList = _p.gridIdColumnIndexMap()[ i ];518 $.each( _rowList, function( _k, _item ){519 _item.rowIndex > _p._maxRowY && ( _p._maxRowY = _item.rowIndex );520 });521 }522 var _fcol = _p.gridIdColumnIndexMap()[0]523 , _first, _last524 , _lcol = _p.gridIdColumnIndexMap()[ _p.gridMaxColumn() - 1]525 ;526 if( _fcol && _fcol.length ){527 var _fdata = _fcol[0];528 if( _fdata.nodes && _fdata.nodes.length ){529 _first = _fdata.nodes.first();530 _last = _fdata.nodes.last();531 _fdata.rowIndex = _first.rowIndex + ( _last.rowIndex - _first.rowIndex ) / 2;532 }533 }534 }535 , fixNodesRowIndex:536 function(){537 var _p = this;538 for( var i = 0; i <= _p.gridMaxColumn(); i++ ){539 var _rowList = _p.gridIdColumnIndexMap()[ i ]540 , _nextList = _p.gridIdColumnIndexMap()[ i + 1 ]541 ;542 $.each( _rowList, function( _k, _item ){543 var _preItem = _rowList[ _k - 1 ]544 , _nextItem = _rowList[ _k + 1 ]545 , _oldIx = _item.rowIndex546 , _nodes = _item.nodes547 , _pid = _item.pid548 , _pitem = _p.gridIdMap( _pid ) || {}549 , _fdata, _ldata550 , _fitem, _litem551 , _midY 552 , _spaceY553 , _minY, _maxY554 ;555 if( _nodes && _nodes.length ){556 if( _nodes.length > 1 ){557 _fdata = _nodes.first();558 _ldata = _nodes.last();559 _midY = _fdata.rowIndex + ( _ldata.rowIndex - _fdata.rowIndex ) / 2;560 _spaceY = _oldIx - _midY;561 _minY = _fdata.rowIndex + _spaceY;562 _maxY = _ldata.rowIndex + _spaceY;563 if( _spaceY === 0 ) {564 return;565 }566 if( _fdata.prev && _minY <= _fdata.prev.rowIndex ){567 _spaceY = _fdata.prev.rowIndex + 1 - _minY;568 _minY += _spaceY;569 _maxY += _spaceY;570 _p.fixItemDataAndNext( _fdata, _minY - _fdata.rowIndex );571 _p.fixItemDataAndNext( _item, _spaceY );572 _p.fixItemParentDataAndNext( _item, _spaceY );573 }else if( _ldata.next && _maxY >= _ldata.next.rowIndex ){574 _p.fixItemDataAndNext( _fdata, _maxY - _ldata.rowIndex );575 }else{576 //_p.fixItemDataAndNext( _fdata, _maxY - _ldata.rowIndex );577 //JC.log( _item.name, _fdata.name, _ldata.name, _spaceY );578 _p.fixItemDataAndNext( _fdata, _spaceY );579 }580 }else{581 _fdata = _nodes.first();582 //JC.log( _item.name, _item.id, JC.f.ts(), _item.rowIndex, _fdata.rowIndex, _fdata.name );583 if( _item.rowIndex === _fdata.rowIndex ) return;584 //JC.log( 1 );585 _maxY = Math.max( _item.rowIndex, _fdata.rowIndex );586 if( _item.rowIndex > _fdata.rowIndex ){587 //JC.log( 2 );588 _p.fixItemDataAndNext( _fdata, _item.rowIndex - _fdata.rowIndex );589 }else if( _item.rowIndex < _fdata.rowIndex ){590 //JC.log( 3 );591 _p.fixItemDataAndNext( _item, _fdata.rowIndex - _item.rowIndex );592 var _newIx = _item.rowIndex;593 _p.fixItemParentDataAndNext( _item, _newIx - _oldIx );594 //JC.log( _item.name, _item.id, JC.f.ts(), _pitem.name, _pitem.id );595 }else{596 //JC.log( 4 );597 }598 }599 }600 });601 }602 }603 , fixTargetNodesRowIndex:604 function(){605 var _p = this;606 for( var i = 0; i <= _p.gridMaxColumn(); i++ ){607 var _rowList = _p.gridIdColumnIndexMap()[ i ]608 , _nextList = _p.gridIdColumnIndexMap()[ i + 1 ]609 ;610 $.each( _rowList, function( _k, _item ){611 var _preItem = _rowList[ _k - 1 ]612 , _nextItem = _rowList[ _k + 1 ]613 , _oldIx = _item.rowIndex614 , _nodes = _item.nodes615 , _pid = _item.pid616 , _fdata, _ldata617 , _fitem, _litem618 , _midY 619 , _spaceY620 , _minY, _maxY621 ;622 if( _pid && _pid.length ){623 if( _pid.length > 1 ){624 _fdata = _p.gridIdMap( _pid.first() );625 _ldata = _p.gridIdMap( _pid.last() );626 _midY = _fdata.rowIndex + ( _ldata.rowIndex - _fdata.rowIndex ) / 2627 if( _item.prev && _item.prev.rowIndex >= _midY ){628 }else if( _item.next && _item.next.rowIndex <= _midY ){629 //JC.log( _item.name, _item.id, _item.next.name, _item.next.id );630 _p.fixItemDataAndNext( _item, _midY - _item.rowIndex );631 }else{632 _spaceY = _midY - _item.rowIndex;633 _item.rowIndex = _midY;634 _p.fixItemChildDataAndNext( _item, _spaceY );635 }636 }else{637 _fdata = _p.gridIdMap( _pid.first() );638 if( _fdata.targetNode ){639 if( _item.next && _fdata.rowIndex >= _item.next.rowIndex ){640 _spaceY = _fdata.rowIndex - _item.rowIndex;641 _p.fixItemDataAndNext( _item, _spaceY );642 }else{643 _spaceY = _fdata.rowIndex - _item.rowIndex;644 _item.rowIndex = _fdata.rowIndex;645 _p.fixItemChildDataAndNext( _item, _spaceY );646 }647 }648 }649 }650 });651 }652 }653 , fixItemChildDataAndNext:654 function( _item, _spaceY ){655 var _p = this, _nextSpaceY, _newIx;656 if( !( _item && _item.nodes && _item.nodes.length ) ) return;657 $.each( _item.nodes, function( _k, _sitem ){658 _sitem.rowIndex += _spaceY;659 _p.fixItemChildDataAndNext( _sitem, _spaceY );660 });661 }662 , fixItemParentDataAndNext:663 function( _item, _spaceY, _isRealY ){664 var _p = this, _nextSpaceY, _newIx;665 if( !( _item && _item.pid && _item.pid.length ) ) return;666 var _pitem = _p.gridIdMap( _item.pid.first() )667 , _fdata, _ldata, _midY668 ;669 if( !( _pitem ) ) return;670 _p.fixItemDataAndNext( _pitem, _spaceY );671 _p.fixItemParentDataAndNext( _pitem, _spaceY, _isRealY );672 }673 , fixItemDataAndNext:674 function( _node, _spaceY ){675 while( _node ){676 _node.rowIndex += _spaceY;677 _node = _node.next;678 }679 }680 , fixRealRowIndex:681 function(){682 var _p = this, _sx = 0, _sy = 0, _minY = 0;683 for( var i = 0; i <= _p.gridMaxColumn(); i++ ){684 var _rowList = _p.gridIdColumnIndexMap()[ i ]685 ;686 $.each( _rowList, function( _k, _item ){687 var _rowIx = _item.rowIndex - _p.gridOffsetRowIndex()688 ;689 _item.rowIndex = _rowIx;690 _rowIx < _minY && ( _minY = _rowIx );691 });692 }693 if( _minY < 0 ){694 _minY = Math.abs( _minY );695 for( var i = 0; i <= _p.gridMaxColumn(); i++ ){696 var _rowList = _p.gridIdColumnIndexMap()[ i ]697 ;698 $.each( _rowList, function( _k, _item ){699 _item.rowIndex += _minY;700 });701 }702 }703 }704 , initRowIndex:705 function(){706 var _p = this;707 for( var i = 0; i <= _p.gridMaxColumn(); i++ ){708 //JC.log( i, JC.f.ts() );709 var _rowList = _p.gridIdColumnIndexMap()[ i ]710 , _preList = _p.gridIdColumnIndexMap()[ i - 1 ]711 , _len = _rowList.length712 , _preLen = _preList ? _preList.length : 0713 ;714 //JC.dir( _rowList );715 //716 _preList && ( _preList = _preList.slice().reverse() );717 /**718 * 这里的逻辑认为 起始节点 和 结束节点都只有一个719 */720 if( i === 0 ){721 $.each( _rowList, function( _k, _item ){722 _item.rowIndex = _p.gridOffsetRowIndex();723 });724 continue;725 }726 var _minRowIndex = _p.gridOffsetRowIndex()727 , _maxRowIndex = _p.gridOffsetRowIndex()728 , _itemIndexLen = 1729 , _startIndex = _p.gridOffsetRowIndex()730 ;731 if( _rowList.length > 1 ){732 _itemIndexLen = _rowList.length * 2;733 }734 _startIndex = _startIndex - ( _itemIndexLen / 2 );735 _startIndex += 1;736 $.each( _rowList, function( _k, _item ){737 _item.rowIndex = _startIndex + _k * 2;738 //JC.log( i, _k, _item.rowIndex );739 });740 //JC.log( i, _startIndex );741 }742 }743 , gridMaxColumn:744 function( _setter ){745 typeof _setter != 'undefined' && ( this.grid().maxColumn = _setter );746 return this.grid().maxColumn;747 }748 , gridRowIndexPad:749 function( _setter ){750 typeof _setter != 'undefined' && ( this.grid().rowIndexPad = _setter );751 return this.grid().rowIndexPad;752 }753 , initColumnIndexMap:754 function(){755 var _p = this;756 $.each( _p.gridIdColumnIndexList(), function( _k, _item ){757 if( _item.columnIndex in _p.gridIdColumnIndexMap() ){758 _p.gridIdColumnIndexMap()[ _item.columnIndex ].push( _item );759 }else{760 _p.gridIdColumnIndexMap()[ _item.columnIndex ] = [ _item ];761 }762 });763 }764 , initColumnRelationship:765 function(){766 var _p = this;767 $.each( _p.gridIdColumnIndexMap(), function( _ix, _list ){768 $.each( _list, function( _k, _item ){769 var _prev = _list[ _k - 1 ]770 ;771 _item.prev = _prev;772 _prev && ( _prev.next = _item );773 _item.next = null;774 });775 });776 }777 , initIdColumnIndex:778 function( _data, _id, _ix, _processSelf, _count ){779 var _p = this, _childIx = _ix + 1, _targetNodeIx = _childIx + 1;780 //JC.log( _ix, _data.name, _id, JC.f.ts() );781 if( ( 'columnIndex' in _data ) && _ix < _data.columnIndex ){782 _ix = _data.columnIndex;783 }784 if( !( _id in _p.gridIdMap() ) ){785 _p.gridIdColumnIndexList().push( _data );786 }787 _data.id = _id;788 _data.pid = _data.pid || [];789 _data.columnIndex = _ix;790 _p.gridIdColumnIndex()[ _id ] = _data;791 _p.gridIdMap()[ _id ] = _data;792 _data.zindex = _count++;793 _ix > _p.gridMaxColumn() && _p.gridMaxColumn( _ix );794 if( _data.nodes && _data.nodes.length ){795 var _targetNodes = {};796 $.each( _data.nodes, function( _k, _item ){797 _item.pid = _item.pid || [];798 _item.pid.push( _id );799 if( ( 'targetNode' in _item ) && _p.chartData().targetNodes && ( _item.targetNode in _p.chartData().targetNodes ) ){800 _targetNodes[ _item.targetNode ] = _item.targetNode;801 _p.chartData().targetNodes[ _item.targetNode ].pid = _p.chartData().targetNodes[ _item.targetNode ].pid || [];802 _p.chartData().targetNodes[ _item.targetNode ].pid.push( _item.id );803 }804 _p.initIdColumnIndex( _item, _item.id, _childIx, false, _count );805 });806 $.each( _targetNodes, function( _k, _item ){807 _p.initIdColumnIndex( _p.chartData().targetNodes[ _k ], _k, _targetNodeIx, true, _count );808 });809 } 810 if( _processSelf && ( 'targetNode' in _data ) && _p.chartData().targetNodes && ( _data.targetNode in _p.chartData().targetNodes ) ){811 _p.chartData().targetNodes[ _data.targetNode ].pid = _p.chartData().targetNodes[ _data.targetNode ].pid || [];812 _p.chartData().targetNodes[ _data.targetNode ].pid.push( _id );813 _p.initIdColumnIndex( _p.chartData().targetNodes[ _data.targetNode ], _data.targetNode, _childIx, true, _count );814 }815 }816 , buildLayout:817 function(){818 var _p = this;819 _p._container = $( '<div class="js_cfcContainer"></div>' );820 _p._layout = $( '<div class="js_cfcLayout"></div>' );821 _p._raphaelPlaceholder = $( '<div class="js_cfcRaphael" style="position: absolute;"></div>' );822 _p._box = $( '<div class="js_cfcBox" style=""></div>' );823 _p._raphaelPlaceholder.appendTo( _p._layout );824 _p._box.appendTo( _p._layout );825 _p._layout.appendTo( _p._container );826 _p._container.appendTo( _p.selector() );827 }828 , layout: function(){ return this._layout; }829 , box: function(){ return this._box; }830 , raphaelPlaceholder: function(){ return this._raphaelPlaceholder; }831 , width: function(){ return Math.abs( this._maxX - this._minX ); }832 , height: function(){ return Math.abs( this._maxY - this._minY + 5 ); }833 , listHasChildline:834 function( _list ){835 var _r = false;836 $.each( _list, function( _k, _item ){837 if( ( _item.nodes && _item.nodes.length > 1 ) ){838 _r = true;839 return false;840 }841 });842 return _r;843 }844 , listHasParentline:845 function( _list ){846 var _r = false, _tmp = {};847 $.each( _list, function( _k, _item ){848 if( _item.targetNode in _tmp ){849 _r = true;850 return false;851 }852 if( _item.targetNode && !( _item.targetNode in _tmp ) ){853 _tmp[ _item.targetNode ] = 1;854 }855 });856 return _r;857 }858 , colors:859 function(){860 var _p = this;861 if( !_p._colors ){862 _p._colors = _p._buildInColors;863 if( _p.colorsData() ){864 $.each( _p.colorsData(), function( _k, _item ){865 if( _k in _p._colors ){866 if( $.isPlainObject( _item ) ){867 JC.f.extendObject( _p._colors[ _k ], _item );868 }869 }else{870 _p._colors[ _k ] = _item;871 }872 });873 }874 //JC.dir( _p._colors );875 }876 return _p._colors;877 }878 , _buildInColors: {879 line: {880 'stroke': '#E1E1E1', 'stroke-width': 2881 }882 , icon: {883 'stroke': '#E1E1E1', 'stroke-width': 2, 'fill': '#F2F2F2'884 }885 }886 });887 JC.f.extendObject( FlowChart.View.prototype, {888 init:889 function(){890 //JC.log( 'FlowChart.View.init:', new Date().getTime() );891 }892 , draw:893 function(){894 var _p = this, _st, _et;895 if( !( _p._model.chartData() && _p._model.chartData().name ) ) return;896 _st = JC.f.ts();897 _p._model.buildLayout();898 _p._model.initGrid();899 _p._model.layout().css( { 900 'height': Math.abs( _p._model.maxY() ) + 'px'901 } );902 _p.showGrid();903 _p.showLine();904 JC.PopTips.init( _p.selector() );905 _et = JC.f.ts();906 //JC.log( 'time span:', _et - _st );907 }908 , showLine:909 function(){910 var _p = this, _rh, _raphael, _y = Math.abs( _p._model.minY() ), _ypad = 0;911 _rh = _raphael = Raphael( _p._model.raphaelPlaceholder()[0], _p._model.width(), _p._model.height() );912 !isIE && ( _ypad = 1 );913 for( var i = 0; i <= _p._model.gridMaxColumn(); i++ ){914 var _rowList = _p._model.gridIdColumnIndexMap()[ i ]915 , _hasChildline = _p._model.listHasChildline( _rowList )916 , _hasParentline = _p._model.listHasParentline( _rowList )917 , _columnX = _p._model.columnX( i )918 , _preColumnX = _p._model.columnX( i - 1 )919 , _columnWidth = _p._model.columnWidth( i )920 , _preColumnWidth = _p._model.columnWidth( i - 1 )921 , _startX = _columnX + _columnWidth922 , _realStartX923 , _lineWidth = _p._model.lineWidth()924 , _xpad = 0925 ;926 if( _hasParentline ){927 _lineWidth += _p._model.childLineWidth();928 }929 if( _hasChildline ){930 _lineWidth += _p._model.parentLineWidth();931 }932 //JC.log( i, _columnX, _columnWidth, _startX );933 $.each( _rowList, function( _k, _item ){934 var _node = _p._model.item( _item.id )935 , _pid = _item.pid936 , _nodes = _item.nodes937 , _subitem938 , _realStartX939 , _realY940 , _fitem, _litem941 , _fnode, _lnode942 , _ex, _sx, _sy, _ey943 , _tmpX944 , _midY945 , _tmpY, _tmpY1, _tmpY2946 , _endX 947 , _sdata, _snode948 , _path949 ;950 if( !( _pid || _nodes ) ) return; 951 if( _pid && _pid.length ){952 _fitem = _p._model.gridIdMap( _pid.first() );953 _fnode = _p._model.item( _fitem.id );954 if( _pid.length > 1 ){955 _realStartX = _preColumnX + _preColumnWidth + _p._model.parentLineWidth();956 _litem = _p._model.gridIdMap( _pid.last() );957 _lnode = _p._model.item( _litem.id );958 _midY = _item.y + Math.abs( _p._model.minY() ) + _node.outerHeight() / 2 + _ypad;959 _tmpY1 = _fitem.y + Math.abs( _p._model.minY() ) + _fnode.outerHeight() / 2 + _ypad;960 _tmpY2 = _litem.y + Math.abs( _p._model.minY() ) + _lnode.outerHeight() / 2 + _ypad;961 _endX = _item.x - 18;962 _rh.path( JC.f.printf( 963 '{0}M{1} {2}L{3} {4}M{5} {6}L{7} {8}'964 , ''965 , _realStartX, _tmpY1966 , _realStartX, _tmpY2967 , _realStartX, _midY968 , _endX, _midY969 )).attr( _p._model.colors().line );970 $.each( _pid, function( _sk, _sitem ){971 _sdata = _p._model.gridIdMap( _sitem );972 _snode = _p._model.item( _sdata.id );973 _tmpY = _sdata.y + Math.abs( _p._model.minY() ) + _snode.outerHeight() / 2 + _ypad;974 _rh.path( JC.f.printf( 975 '{0}M{1} {2}L{3} {4}'976 , ''977 , _sdata.x, _tmpY978 , _realStartX, _tmpY979 )).attr( _p._model.colors().line );980 });981 _rh.JCTriangle( 16, _endX, _midY, _p._model.colors().icon );982 }else if( _fitem && _pid.length === 1 && ( 'targetNode' in _fitem ) ){983 _realStartX = _preColumnX + _fnode.outerWidth();984 _realY = _fitem.y + _fnode.outerHeight() / 2;985 _item.y = _fitem.y;986 _rh.path( JC.f.printf( 987 '{0}M{1} {2}L{3} {4}'988 , '', _realStartX, _realY + _ypad, _item.x - 18, _realY + _ypad989 )).attr( _p._model.colors().line );990 _rh.JCTriangle( 16, _item.x - 18, _realY + _ypad, _p._model.colors().icon );991 }992 }993 if( _nodes && _nodes.length ){994 if( _nodes.length > 1 ){995 _sx = _item.x + _node.outerWidth();996 _fitem = _nodes.first();997 _litem = _nodes.last();998 _fnode = _p._model.item( _fitem.id );999 _lnode = _p._model.item( _litem.id );1000 //JC.log( _item.id, _fitem.name, _litem.name );1001 _ex = _fitem.x;1002 _realStartX = _ex - _p._model.childLineWidth();1003 _midY = _item.y + Math.abs( _p._model.minY() ) + _node.outerHeight() / 2 + _ypad;1004 _rh.path( JC.f.printf( 1005 '{0}M{1} {2}L{3} {4}'1006 , ''1007 , _sx, _midY1008 , _realStartX - 18, _midY1009 )).attr( _p._model.colors().line );1010 _rh.JCTriangle( 16, _realStartX - 18, _midY, _p._model.colors().icon );1011 _tmpY1 = _fitem.y + Math.abs( _p._model.minY() ) + _fnode.outerHeight() / 2 + _ypad;1012 _tmpY2 = _litem.y + Math.abs( _p._model.minY() ) + _lnode.outerHeight() / 2 + _ypad;1013 _endX = _item.x - 18;1014 _rh.path( JC.f.printf( 1015 '{0}M{1} {2}L{3} {4}'1016 , ''1017 , _realStartX, _tmpY11018 , _realStartX, _tmpY21019 )).attr( _p._model.colors().line );1020 $.each( _nodes, function( _sk, _sitem ){1021 _sdata = _sitem;1022 _snode = _p._model.item( _sdata.id );1023 _tmpY = _sdata.y + Math.abs( _p._model.minY() ) + _snode.outerHeight() / 2 + _ypad;1024 _rh.path( JC.f.printf( 1025 '{0}M{1} {2}L{3} {4}'1026 , ''1027 , _realStartX, _tmpY1028 , _sdata.x, _tmpY1029 )).attr( _p._model.colors().line );1030 });1031 }1032 if( _nodes.length === 1 ){1033 _realStartX = _columnX + _node.outerWidth();1034 _realY = _item.y + _node.outerHeight() / 2;1035 _subitem = _nodes[0];1036 _rh.path( JC.f.printf( 1037 '{0}M{1} {2}L{3} {4}'1038 , '', _realStartX, _realY + _y + _ypad, _subitem.x - 18, _realY + _y + _ypad1039 )).attr( _p._model.colors().line );1040 _rh.JCTriangle( 16, _subitem.x - 18, _realY + _y + _ypad, _p._model.colors().icon );1041 }1042 }1043 });1044 }1045 }1046 , showGrid:1047 function(){1048 var _p = this;1049 for( var i = 0; i <= _p._model.gridMaxColumn(); i++ ){1050 var _rowList = _p._model.gridIdColumnIndexMap()[ i ]1051 ;1052 $.each( _rowList, function( _k, _item ){1053 var _node = _p._model.item( _item.id )1054 ;1055 _node.css({1056 'left': _item.x + 'px', 'top': _item.y + 'px'1057 });1058 _p.notification( JC.FlowChart.Model.ITEM_INITED, [ _node, _item, _rowList, _p._model.data() ] );1059 });1060 }1061 }1062 });1063 FlowChart.TIPS_TPL =1064 [1065 '<span class="js_compPopTips" style="display:inline-block;"'1066 ,'htmlContent="|script"'1067 ,'theme="white"'1068 ,'arrowposition="bottom"'1069 ,'triggerType="hover"'1070 ,'popTipsMinWidth="100"'1071 ,'popTipsMinHeight="50"'1072 ,'>'1073 ,'<span>{0}</span>'1074 ,'<script type="text/template"><div class="js_cfcItemTips js_cfcItemTips_{2}">{1}</div><\/script>'1075 ,'</span>'1076 ].join('');1077 function distanceAngleToPoint( _distance, _angle){1078 var _radian = _angle * Math.PI / 180; 1079 return {1080 x: ( Math.cos( _radian ) * _distance )1081 , y: ( Math.sin( _radian ) * _distance )1082 }1083 }1084 _jdoc.ready( function(){1085 Raphael.fn.JCTriangle =1086 function( _sideLength, _x, _y, _params, _offsetAngle ){1087 !_sideLength && ( _sideLength = 16 );1088 !_x && ( _x = 0 );1089 !_y && ( _y = _sideLength / 2 );1090 _y += 1;1091 typeof _offsetAngle == 'undefined' && ( _offsetAngle = 180 );1092 var _p1 = distanceAngleToPoint( _sideLength, 330 )1093 , _p2 = distanceAngleToPoint( _sideLength, 30 )1094 , _p3 = distanceAngleToPoint( _sideLength, 120 )1095 ;1096 _p1.x = parseInt( _p1.x + _x );1097 _p1.y = parseInt( _p1.y + _y );1098 _p2.x = parseInt( _p2.x + _x );1099 _p2.y = parseInt( _p2.y + _y );1100 var _r = this.path(1101 JC.f.printf( 1102 '{0}M{1} {2}L{3} {4}L{5} {6}L{1} {2}Z'1103 , ''1104 , _x, _y 1105 , _p1.x, _p1.y1106 , _p2.x, _p2.y1107 )1108 );1109 _r.rotate( _offsetAngle );1110 _params && _r.attr( _params );1111 return _r;1112 };1113 JC.f.safeTimeout( function(){1114 FlowChart.autoInit && FlowChart.init();1115 }, null, 'JCFlowChart_INIT', 1);1116 });1117 return JC.FlowChart;1118});}( typeof define === 'function' && define.amd ? define : 1119 function ( _name, _require, _cb ) { 1120 typeof _name == 'function' && ( _cb = _name );1121 typeof _require == 'function' && ( _cb = _require ); 1122 _cb && _cb(); 1123 }1124 , window1125 )...

Full Screen

Full Screen

user.js

Source:user.js Github

copy

Full Screen

1/*页面js模板,必须有init方法*/2(function () {3 var companyMap;4 var departmentMap;5 var userMap;6 var userData = {};7 var getHeadImg = function (user) {8 var url = '';9 switch (user.img) {10 case '0':11 url += 'images/on-girl.jpg';12 break;13 case '1':14 url += 'images/on-boy.jpg';15 break;16 default:17 url += config.webapi + 'learun/adms/user/img?data=' + user.id;18 break;19 }20 return url;21 };22 var page = {23 isScroll: true,24 init: function ($page, param) {25 companyMap = {};26 departmentMap = {};27 userMap = {};28 // 人员列表数据初始化29 learun.clientdata.getAll('user', {30 callback: function (data) {31 userData = data;32 $.each(data, function (_id, _item) {33 _item.id = _id;34 if (_item.departmentId) {35 userMap[_item.departmentId] = userMap[_item.departmentId] || [];36 userMap[_item.departmentId].push(_item);37 }38 else if (_item.companyId) {39 userMap[_item.companyId] = userMap[_item.companyId] || [];40 userMap[_item.companyId].push(_item);41 }42 });43 var $list = $page.find('#lr_select_user_list');44 if (param.op.departmentId) {45 userData = {};46 // 加载人员47 $.each(userMap[param.op.departmentId] || [], function (_index, _item) {48 userData[_item.id] = _item;49 var _html = '\50 <div class="lr-list-item user lr-list-item-onlyuser" data-value="'+ _item.id + '" >\51 <img src="'+ getHeadImg(_item) + '" >\52 <span >' + _item.name + '</span>\53 </div>';54 $list.append(_html);55 });56 }57 else if (param.op.companyId) {58 userData = {};59 // 加载人员60 $.each(userMap[param.op.companyId] || [], function (_index, _item) {61 userData[_item.id] = _item;62 var _html = '\63 <div class="lr-list-item user lr-list-item-onlyuser" data-value="'+ _item.id + '" >\64 <img src="'+ getHeadImg(_item) + '" >\65 <span >' + _item.name + '</span>\66 </div>';67 $list.append(_html);68 });69 }70 else {71 // 公司列表数据初始化72 learun.clientdata.getAll('company', {73 callback: function (data) {74 $.each(data, function (_id, _item) {75 companyMap[_item.parentId] = companyMap[_item.parentId] || [];76 _item.id = _id;77 companyMap[_item.parentId].push(_item);78 });79 $.each(companyMap["0"], function (_index, _item) {80 var _html = '\81 <div class="lr-list-item" >\82 <a class="lr-nav-left company" data-value="'+ _item.id + '" >' + _item.name + '</a>\83 </div>';84 $list.append(_html);85 });86 // 部门列表数据初始化87 learun.clientdata.getAll('department', {88 callback: function (data) {89 $.each(data, function (_id, _item) {90 _item.id = _id;91 if (_item.parentId === "0") {92 departmentMap[_item.companyId] = departmentMap[_item.companyId] || [];93 departmentMap[_item.companyId].push(_item);94 }95 else {96 departmentMap[_item.parentId] = departmentMap[_item.parentId] || [];97 departmentMap[_item.parentId].push(_item);98 }99 });100 }101 });102 }103 });104 }105 }106 });107 108 // 注册点击事件109 $('#lr_select_user_list').on('tap', function (e) {110 e = e || window.event;111 var et = e.target || e.srcElement;112 var $et = $(et);113 if (et.tagName === 'IMG' || et.tagName === 'SPAN') {114 $et = $et.parent();115 }116 var $list = $('<div class="lr-user-list" ></div>');117 var flag = false;118 var id = $et.attr('data-value');119 if ($et.hasClass('company')) {120 if ($et.hasClass('bottom')) {121 $et.removeClass('bottom');122 $et.parent().find('.lr-user-list').remove();123 }124 else {125 $list.css({ 'padding-left': '10px' });126 // 加载人员127 $.each(userMap[id] || [], function (_index, _item) {128 var _html = '\129 <div class="lr-list-item user" data-value="'+ _item.id + '" >\130 <img src="'+ getHeadImg(_item) + '" >\131 <span >' + _item.name + '</span>\132 </div>';133 $list.append(_html);134 flag = true;135 });136 // 加载部门137 $.each(departmentMap[id] || [], function (_index, _item) {138 var _html = '\139 <div class="lr-list-item" >\140 <a class="lr-nav-left department" data-value="'+ _item.id + '" >' + _item.name + '</a>\141 </div>';142 $list.append(_html);143 flag = true;144 });145 // 加载公司146 $.each(companyMap[id] || [], function (_index, _item) {147 var _html = '\148 <div class="lr-list-item" >\149 <a class="lr-nav-left company" data-value="'+ _item.id + '" >' + _item.name + '</a>\150 </div>';151 $list.append(_html);152 flag = true;153 });154 if (flag) {155 $et.parent().append($list);156 }157 $et.addClass('bottom');158 }159 $list = null;160 return false;161 }162 else if ($et.hasClass('department')) {163 if ($et.hasClass('bottom')) {164 $et.removeClass('bottom');165 $et.parent().find('.lr-user-list').remove();166 }167 else {168 $list.css({ 'padding-left': '10px' });169 // 加载人员170 $.each(userMap[id] || [], function (_index, _item) {171 var _html = '\172 <div class="lr-list-item user" data-value="'+ _item.id + '" >\173 <img src="'+ getHeadImg(_item) + '" >\174 <span >' + _item.name + '</span>\175 </div>';176 $list.append(_html);177 flag = true;178 });179 // 加载部门180 $.each(departmentMap[id] || [], function (_index, _item) {181 var _html = '\182 <div class="lr-list-item" >\183 <a class="lr-nav-left department" data-value="'+ _item.id + '" >' + _item.name + '</a>\184 </div>';185 $list.append(_html);186 flag = true;187 });188 if (flag) {189 $et.parent().append($list);190 }191 $et.addClass('bottom');192 }193 $list = null;194 return false;195 }196 else if ($et.hasClass('user')) {197 param.callback(userData[id], param.op, param.$this);198 learun.nav.closeCurrent();199 $list = null;200 return false;201 }202 });203 // 搜索事件204 $page.find('input').on('input propertychange', function () {205 var keyword = $(this).val();206 var $list = $('#lr_select_user_list');207 if (keyword) {208 $list.html("");209 $.each(userData, function (_index, _item) {210 if (_item.name.indexOf(keyword) !== -1) {211 var _html = '\212 <div class="lr-list-item user lr-list-item-onlyuser" data-value="'+ _item.id + '" >\213 <img src="'+ getHeadImg(_item) + '" >\214 <span >' + _item.name + '</span>\215 </div>';216 $list.append(_html);217 }218 });219 }220 else {221 $list.html("");222 if (param.op.departmentId) {223 // 加载人员224 $.each(userMap[param.op.departmentId] || [], function (_index, _item) {225 var _html = '\226 <div class="lr-list-item user lr-list-item-onlyuser" data-value="'+ _item.id + '" >\227 <img src="'+ getHeadImg(_item) + '" >\228 <span >' + _item.name + '</span>\229 </div>';230 $list.append(_html);231 });232 }233 else if (param.op.companyId) {234 // 加载人员235 $.each(userMap[param.op.companyId] || [], function (_index, _item) {236 var _html = '\237 <div class="lr-list-item user lr-list-item-onlyuser" data-value="'+ _item.id + '" >\238 <img src="'+ getHeadImg(_item) + '" >\239 <span >' + _item.name + '</span>\240 </div>';241 $list.append(_html);242 });243 }244 else {245 $.each(companyMap["0"], function (_index, _item) {246 var _html = '\247 <div class="lr-list-item" >\248 <a class="lr-nav-left company" data-value="'+ _item.id + '" >' + _item.name + '</a>\249 </div>';250 $list.append(_html);251 });252 }253 254 }255 });256 },257 destroy: function (pageinfo) {258 companyMap = null;259 departmentMap = null;260 userMap = null;261 }262 };263 return page;...

Full Screen

Full Screen

FuseUtils.js

Source:FuseUtils.js Github

copy

Full Screen

1import * as colors from '@material-ui/core/colors';2import _ from '@lodash';3class EventEmitter {4 constructor()5 {6 this.events = {};7 }8 _getEventListByName(eventName)9 {10 if ( typeof this.events[eventName] === 'undefined' )11 {12 this.events[eventName] = new Set();13 }14 return this.events[eventName]15 }16 on(eventName, fn)17 {18 this._getEventListByName(eventName).add(fn);19 }20 once(eventName, fn)21 {22 const self = this;23 const onceFn = function (...args) {24 self.removeListener(eventName, onceFn);25 fn.apply(self, args);26 };27 this.on(eventName, onceFn);28 }29 emit(eventName, ...args)30 {31 this._getEventListByName(eventName).forEach(function (fn) {32 fn.apply(this, args);33 }.bind(this));34 }35 removeListener(eventName, fn)36 {37 this._getEventListByName(eventName).delete(fn);38 }39}40class FuseUtils {41 static filterArrayByString(mainArr, searchText)42 {43 if ( searchText === '' )44 {45 return mainArr;46 }47 searchText = searchText.toLowerCase();48 return mainArr.filter(itemObj => {49 return this.searchInObj(itemObj, searchText);50 });51 };52 static searchInObj(itemObj, searchText)53 {54 for ( const prop in itemObj )55 {56 if ( !itemObj.hasOwnProperty(prop) )57 {58 continue;59 }60 const value = itemObj[prop];61 if ( typeof value === 'string' )62 {63 if ( this.searchInString(value, searchText) )64 {65 return true;66 }67 }68 else if ( Array.isArray(value) )69 {70 if ( this.searchInArray(value, searchText) )71 {72 return true;73 }74 }75 if ( typeof value === 'object' )76 {77 if ( this.searchInObj(value, searchText) )78 {79 return true;80 }81 }82 }83 }84 static searchInArray(arr, searchText)85 {86 for ( const value of arr )87 {88 if ( typeof value === 'string' )89 {90 if ( this.searchInString(value, searchText) )91 {92 return true;93 }94 }95 if ( typeof value === 'object' )96 {97 if ( this.searchInObj(value, searchText) )98 {99 return true;100 }101 }102 }103 }104 static searchInString(value, searchText)105 {106 return value.toLowerCase().includes(searchText);107 }108 static generateGUID()109 {110 function S4()111 {112 return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);113 }114 return S4() + S4();115 }116 static toggleInArray(item, array)117 {118 if ( array.indexOf(item) === -1 )119 {120 array.push(item);121 }122 else123 {124 array.splice(array.indexOf(item), 1);125 }126 }127 static handleize(text)128 {129 return text.toString().toLowerCase()130 .replace(/\s+/g, '-') // Replace spaces with -131 .replace(/\W+/g, '') // Remove all non-word chars132 .replace(/--+/g, '-') // Replace multiple - with single -133 .replace(/^-+/, '') // Trim - from start of text134 .replace(/-+$/, ''); // Trim - from end of text135 }136 static setRoutes(config, defaultAuth)137 {138 let routes = [...config.routes];139 if ( config.settings || config.auth )140 {141 routes = routes.map((route) => {142 let auth = config.auth ? [...config.auth] : defaultAuth || null;143 auth = route.auth ? [...auth, ...route.auth] : auth;144 return {145 ...route,146 settings: {...config.settings, ...route.settings},147 auth148 };149 });150 }151 return [...routes];152 }153 static generateRoutesFromConfigs(configs, defaultAuth)154 {155 let allRoutes = [];156 configs.forEach((config) => {157 allRoutes = [158 ...allRoutes,159 ...this.setRoutes(config, defaultAuth)160 ]161 });162 return allRoutes;163 }164 static findById(o, id)165 {166 //Early return167 if ( o.id === id )168 {169 return o;170 }171 let result, p;172 for ( p in o )173 {174 if ( o.hasOwnProperty(p) && typeof o[p] === 'object' )175 {176 result = this.findById(o[p], id);177 if ( result )178 {179 return result;180 }181 }182 }183 return result;184 }185 static getFlatNavigation(navigationItems, flatNavigation)186 {187 flatNavigation = flatNavigation ? flatNavigation : [];188 for ( const navItem of navigationItems )189 {190 if ( navItem.type === 'subheader' )191 {192 continue;193 }194 if ( navItem.type === 'item' )195 {196 flatNavigation.push({197 id : navItem.id,198 title: navItem.title,199 type : navItem.type,200 icon : navItem.icon || false,201 url : navItem.url,202 auth : navItem.auth || null203 });204 continue;205 }206 if ( navItem.type === 'collapse' || navItem.type === 'group' )207 {208 if ( navItem.children )209 {210 this.getFlatNavigation(navItem.children, flatNavigation);211 }212 }213 }214 return flatNavigation;215 }216 static randomMatColor(hue)217 {218 hue = hue ? hue : '400';219 const mainColors = [220 'red',221 'pink',222 'purple',223 'deepPurple',224 'indigo',225 'blue',226 'lightBlue',227 'cyan',228 'teal',229 'green',230 'lightGreen',231 'lime',232 'yellow',233 'amber',234 'orange',235 'deepOrange'236 ];237 const randomColor = mainColors[Math.floor(Math.random() * mainColors.length)];238 return colors[randomColor][hue];239 }240 static difference(object, base)241 {242 function changes(object, base)243 {244 return _.transform(object, function (result, value, key) {245 if ( !_.isEqual(value, base[key]) )246 {247 result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;248 }249 });250 }251 return changes(object, base);252 }253 static EventEmitter = EventEmitter;254 static updateNavItem(nav, id, item)255 {256 return nav.map(_item => {257 if ( _item.id === id )258 {259 return _.merge({}, _item, item);260 }261 if ( _item.children )262 {263 return _.merge({}, _item, {264 children: this.updateNavItem(_item.children, id, item)265 });266 }267 else268 {269 return _.merge({}, _item);270 }271 })272 }273 static removeNavItem(nav, id)274 {275 return nav.map(_item => {276 if ( _item.id === id )277 {278 return null;279 }280 if ( _item.children )281 {282 return _.merge({}, _.omit(_item, ['children']), {283 children: this.removeNavItem(_item.children, id)284 });285 }286 else287 {288 return _.merge({}, _item);289 }290 }).filter(s => s)291 }292 static prependNavItem(nav, item, parentId)293 {294 if ( !parentId )295 {296 return [297 item,298 ...nav299 ]300 }301 return nav.map(_item => {302 if ( _item.id === parentId && _item.children )303 {304 return {305 _item,306 children: [307 item,308 ..._item.children309 ]310 };311 }312 if ( _item.children )313 {314 return _.merge({}, _item, {315 children: this.prependNavItem(_item.children, item, parentId)316 });317 }318 else319 {320 return _.merge({}, _item);321 }322 })323 }324 static appendNavItem(nav, item, parentId)325 {326 if ( !parentId )327 {328 return [329 ...nav,330 item331 ]332 }333 return nav.map(_item => {334 if ( _item.id === parentId && _item.children )335 {336 return {337 _item,338 children: [339 ..._item.children,340 item341 ]342 };343 }344 if ( _item.children )345 {346 return _.merge({}, _item, {347 children: this.appendNavItem(_item.children, item, parentId)348 });349 }350 else351 {352 return _.merge({}, _item);353 }354 })355 }356 static hasPermission(authArr, userRole)357 {358 /**359 * If auth array is not defined360 * Pass and allow361 */362 if ( authArr === null || authArr === undefined )363 {364 // console.info("auth is null || undefined:", authArr);365 return true;366 }367 /**368 * if auth array is empty means,369 * allow only user role is guest (null or empty[])370 */371 else if ( authArr.length === 0 )372 {373 // console.info("auth is empty[]:", authArr);374 return !userRole || userRole.length === 0;375 }376 /**377 * Check if user has grants378 */379 else380 {381 // console.info("auth arr:", authArr);382 /*383 Check if user role is array,384 */385 if ( userRole && Array.isArray(userRole) )386 {387 return authArr.some(r => userRole.indexOf(r) >= 0);388 }389 /*390 Check if user role is string,391 */392 return authArr.includes(userRole);393 }394 }395}...

Full Screen

Full Screen

contacts.js

Source:contacts.js Github

copy

Full Screen

1/*页面js模板,必须有init方法*/2(function () {3 var companyMap;4 var departmentMap;5 var userMap;6 var getHeadImg = function (user) {7 var url = '';8 switch (user.img) {9 case '0':10 url += 'images/on-girl.jpg';11 break;12 case '1':13 url += 'images/on-boy.jpg';14 break;15 default:16 url += config.webapi + 'learun/adms/user/img?data=' + user.id;17 break;18 }19 return url;20 };21 var page = {22 isScroll: true,23 init: function ($page) {24 companyMap = {};25 departmentMap = {};26 userMap = {};27 // 公司列表数据初始化28 learun.clientdata.getAll('company', {29 callback: function (data) {30 $.each(data, function (_id, _item) {31 companyMap[_item.parentId] = companyMap[_item.parentId] || [];32 _item.id = _id;33 companyMap[_item.parentId].push(_item);34 });35 var $list = $page.find('#lr_contact_companylist');36 $.each(companyMap["0"], function (_index, _item) {37 var _html = '\38 <div class="lr-list-item" >\39 <a class="lr-nav-left company" data-value="'+ _item.id + '" >' + _item.name + '</a>\40 </div>';41 $list.append(_html);42 });43 // 部门列表数据初始化44 learun.clientdata.getAll('department', {45 callback: function (data) {46 $.each(data, function (_id, _item) {47 _item.id = _id;48 if (_item.parentId === "0") {49 departmentMap[_item.companyId] = departmentMap[_item.companyId] || [];50 departmentMap[_item.companyId].push(_item);51 }52 else {53 departmentMap[_item.parentId] = departmentMap[_item.parentId] || [];54 departmentMap[_item.parentId].push(_item);55 }56 });57 // 人员列表数据初始化58 learun.clientdata.getAll('user', {59 callback: function (data) {60 $.each(data, function (_id, _item) {61 _item.id = _id;62 if (_item.departmentId) {63 userMap[_item.departmentId] = userMap[_item.departmentId] || [];64 userMap[_item.departmentId].push(_item);65 }66 else if (_item.companyId) {67 userMap[_item.companyId] = userMap[_item.companyId] || [];68 userMap[_item.companyId].push(_item);69 }70 });71 }72 });73 }74 });75 }76 });77 // 注册点击事件78 $('#lr_contact_companylist').on('tap', function (e) {79 e = e || window.event;80 var et = e.target || e.srcElement;81 var $et = $(et);82 if (et.tagName === 'IMG' || et.tagName === 'SPAN') {83 $et = $et.parent();84 }85 var $list = $('<div class="lr-user-list" ></div>');86 var flag = false;87 var id = $et.attr('data-value');88 if ($et.hasClass('company')) {89 if ($et.hasClass('bottom')) {90 $et.removeClass('bottom');91 $et.parent().find('.lr-user-list').remove();92 }93 else { 94 $list.css({ 'padding-left': '10px' });95 // 加载人员96 $.each(userMap[id] || [], function (_index, _item) {97 var _html = '\98 <div class="lr-list-item user" data-value="'+ _item.id + '" >\99 <img src="'+ getHeadImg(_item) + '" >\100 <span >' + _item.name + '</span>\101 </div>';102 $list.append(_html);103 flag = true;104 });105 // 加载部门106 $.each(departmentMap[id] || [], function (_index, _item) {107 var _html = '\108 <div class="lr-list-item" >\109 <a class="lr-nav-left department" data-value="'+ _item.id + '" >' + _item.name + '</a>\110 </div>';111 $list.append(_html);112 flag = true;113 });114 // 加载公司115 $.each(companyMap[id] || [], function (_index, _item) {116 var _html = '\117 <div class="lr-list-item" >\118 <a class="lr-nav-left company" data-value="'+ _item.id + '" >' + _item.name + '</a>\119 </div>';120 $list.append(_html);121 flag = true;122 });123 if (flag) {124 $et.parent().append($list);125 }126 $et.addClass('bottom');127 }128 $list = null;129 return false;130 }131 else if ($et.hasClass('department')) {132 if ($et.hasClass('bottom')) {133 $et.removeClass('bottom');134 $et.parent().find('.lr-user-list').remove();135 }136 else {137 $list.css({ 'padding-left': '10px' });138 // 加载人员139 $.each(userMap[id] || [], function (_index, _item) {140 var _html = '\141 <div class="lr-list-item user" data-value="'+ _item.id + '" >\142 <img src="'+ getHeadImg(_item) + '" >\143 <span >' + _item.name + '</span>\144 </div>';145 $list.append(_html);146 flag = true;147 });148 // 加载部门149 $.each(departmentMap[id] || [], function (_index, _item) {150 var _html = '\151 <div class="lr-list-item" >\152 <a class="lr-nav-left department" data-value="'+ _item.id + '" >' + _item.name + '</a>\153 </div>';154 $list.append(_html);155 flag = true;156 });157 if (flag) {158 $et.parent().append($list);159 }160 $et.addClass('bottom');161 }162 $list = null;163 return false;164 }165 else if ($et.hasClass('user')){166 var userName = $et.find('span').text();167 learun.nav.go({ path: 'chat', title: userName, isBack: true, isHead: true, param: { hasHistory: true, userId: id }, type: 'right' });168 $list = null;169 return false;170 }171 });172 // 点击搜索框173 $page.find('.searchBox').on('tap', function () {174 learun.nav.go({ path: 'contacts/search', title: '', isBack: true, isHead: true });175 });176 },177 destroy: function (pageinfo) {178 companyMap = null;179 departmentMap = null;180 userMap = null;181 }182 };183 return page;...

Full Screen

Full Screen

action.js

Source:action.js Github

copy

Full Screen

1MM.Action = function() {}2MM.Action.prototype.perform = function() {}3MM.Action.prototype.undo = function() {}4MM.Action.Multi = function(actions) {5 this._actions = actions;6}7MM.Action.Multi.prototype = Object.create(MM.Action.prototype);8MM.Action.Multi.prototype.perform = function() {9 this._actions.forEach(function(action) {10 action.perform();11 });12}13MM.Action.Multi.prototype.undo = function() {14 this._actions.slice().reverse().forEach(function(action) {15 action.undo();16 });17}18MM.Action.InsertNewItem = function(parent, index) {19 this._parent = parent;20 this._index = index;21 this._item = new MM.Item();22}23MM.Action.InsertNewItem.prototype = Object.create(MM.Action.prototype);24MM.Action.InsertNewItem.prototype.perform = function() {25 this._parent.expand(); /* FIXME remember? */26 this._item = this._parent.insertChild(this._item, this._index);27 MM.App.select(this._item);28}29MM.Action.InsertNewItem.prototype.undo = function() {30 this._parent.removeChild(this._item);31 MM.App.select(this._parent);32}33MM.Action.AppendItem = function(parent, item) {34 this._parent = parent;35 this._item = item;36}37MM.Action.AppendItem.prototype = Object.create(MM.Action.prototype);38MM.Action.AppendItem.prototype.perform = function() {39 this._parent.insertChild(this._item);40 MM.App.select(this._item);41}42MM.Action.AppendItem.prototype.undo = function() {43 this._parent.removeChild(this._item);44 MM.App.select(this._parent);45}46MM.Action.RemoveItem = function(item) {47 this._item = item;48 this._parent = item.getParent();49 this._index = this._parent.getChildren().indexOf(this._item);50}51MM.Action.RemoveItem.prototype = Object.create(MM.Action.prototype);52MM.Action.RemoveItem.prototype.perform = function() {53 this._parent.removeChild(this._item);54 MM.App.select(this._parent);55}56MM.Action.RemoveItem.prototype.undo = function() {57 this._parent.insertChild(this._item, this._index);58 MM.App.select(this._item);59}60MM.Action.MoveItem = function(item, newParent, newIndex, newSide) {61 this._item = item;62 this._newParent = newParent;63 this._newIndex = (arguments.length < 3 ? null : newIndex);64 this._newSide = newSide || "";65 this._oldParent = item.getParent();66 this._oldIndex = this._oldParent.getChildren().indexOf(item);67 this._oldSide = item.getSide();68}69MM.Action.MoveItem.prototype = Object.create(MM.Action.prototype);70MM.Action.MoveItem.prototype.perform = function() {71 this._item.setSide(this._newSide);72 if (this._newIndex === null) {73 this._newParent.insertChild(this._item);74 } else {75 this._newParent.insertChild(this._item, this._newIndex);76 }77 MM.App.select(this._item);78}79MM.Action.MoveItem.prototype.undo = function() {80 this._item.setSide(this._oldSide);81 this._oldParent.insertChild(this._item, this._oldIndex);82 MM.App.select(this._newParent);83}84MM.Action.Swap = function(item, diff) {85 this._item = item;86 this._parent = item.getParent();87 var children = this._parent.getChildren();88 var sibling = this._parent.getLayout().pickSibling(this._item, diff);89 90 this._sourceIndex = children.indexOf(this._item);91 this._targetIndex = children.indexOf(sibling);92}93MM.Action.Swap.prototype = Object.create(MM.Action.prototype);94MM.Action.Swap.prototype.perform = function() {95 this._parent.insertChild(this._item, this._targetIndex);96}97MM.Action.Swap.prototype.undo = function() {98 this._parent.insertChild(this._item, this._sourceIndex);99}100MM.Action.SetLayout = function(item, layout) {101 this._item = item;102 this._layout = layout;103 this._oldLayout = item.getOwnLayout();104}105MM.Action.SetLayout.prototype = Object.create(MM.Action.prototype);106MM.Action.SetLayout.prototype.perform = function() {107 this._item.setLayout(this._layout);108}109MM.Action.SetLayout.prototype.undo = function() {110 this._item.setLayout(this._oldLayout);111}112MM.Action.SetShape = function(item, shape) {113 this._item = item;114 this._shape = shape;115 this._oldShape = item.getOwnShape();116}117MM.Action.SetShape.prototype = Object.create(MM.Action.prototype);118MM.Action.SetShape.prototype.perform = function() {119 this._item.setShape(this._shape);120}121MM.Action.SetShape.prototype.undo = function() {122 this._item.setShape(this._oldShape);123}124MM.Action.SetColor = function(item, color) {125 this._item = item;126 this._color = color;127 this._oldColor = item.getOwnColor();128}129MM.Action.SetColor.prototype = Object.create(MM.Action.prototype);130MM.Action.SetColor.prototype.perform = function() {131 this._item.setColor(this._color);132}133MM.Action.SetColor.prototype.undo = function() {134 this._item.setColor(this._oldColor);135}136MM.Action.SetText = function(item, text) {137 this._item = item;138 this._text = text;139 this._oldText = item.getText();140 this._oldValue = item.getValue(); /* adjusting text can also modify value! */141}142MM.Action.SetText.prototype = Object.create(MM.Action.prototype);143MM.Action.SetText.prototype.perform = function() {144 this._item.setText(this._text);145 var numText = Number(this._text);146 if (numText == this._text) { this._item.setValue(numText); }147}148MM.Action.SetText.prototype.undo = function() {149 this._item.setText(this._oldText);150 this._item.setValue(this._oldValue);151}152MM.Action.SetValue = function(item, value) {153 this._item = item;154 this._value = value;155 this._oldValue = item.getValue();156}157MM.Action.SetValue.prototype = Object.create(MM.Action.prototype);158MM.Action.SetValue.prototype.perform = function() {159 this._item.setValue(this._value);160}161MM.Action.SetValue.prototype.undo = function() {162 this._item.setValue(this._oldValue);163}164MM.Action.SetStatus = function(item, status) {165 this._item = item;166 this._status = status;167 this._oldStatus = item.getStatus();168}169MM.Action.SetStatus.prototype = Object.create(MM.Action.prototype);170MM.Action.SetStatus.prototype.perform = function() {171 this._item.setStatus(this._status);172}173MM.Action.SetStatus.prototype.undo = function() {174 this._item.setStatus(this._oldStatus);175}176MM.Action.SetIcon = function(item, icon) {177 this._item = item;178 this._icon = icon;179 this._oldIcon = item.getIcon();180}181MM.Action.SetIcon.prototype = Object.create(MM.Action.prototype);182MM.Action.SetIcon.prototype.perform = function() {183 this._item.setIcon(this._icon);184}185MM.Action.SetIcon.prototype.undo = function() {186 this._item.setIcon(this._oldIcon);187}188MM.Action.SetSide = function(item, side) {189 this._item = item;190 this._side = side;191 this._oldSide = item.getSide();192}193MM.Action.SetSide.prototype = Object.create(MM.Action.prototype);194MM.Action.SetSide.prototype.perform = function() {195 this._item.setSide(this._side);196 this._item.getMap().update();197}198MM.Action.SetSide.prototype.undo = function() {199 this._item.setSide(this._oldSide);200 this._item.getMap().update();...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1function Slider(opt){2 this.wrap = opt.wrap;3 this.left= opt.left;4 this.right = opt.right;5 this._next = opt._next;6 this.prev = opt.prev;7 this.callback = opt.callback;8 this.type=opt.type;9 this.autoPlay = opt.autoPlay;10 this.int();11 this.inDom();12 this.inEvent();13}14Slider.prototype={15 int : function(){16 this._height=$(window).height();17 this.idx=0;18 this._lock = false;19 },20 inDom : function(){21 this._item=this.wrap.find(".main");22 var self=this;23 for(var i=0;i<self._item.length;i++){24 $(self._item[i]).css('-webkit-transform','translate3d(0,'+i*self._height+'px'+',0)');25 }26 },27 inEvent :function(){28 var startY,moveY,offsetY,self=this,len=this._item.length;29 this._item.on("touchstart",function(e){30 self.offsetY=0;31 e.preventDefault();32 self.startY=e.touches[0].screenY;33 34 })35 this._item.on("touchmove",function(e){36 console.log(self._lock);37 if(self._lock){38 return false;39 }40 e.preventDefault();41 self.moveY=e.touches[0].screenY;42 self.offsetY=self.moveY-self.startY;43 var _height=self._height,44 _ofset=self.offsetY;45 for(var i=0;i<len;i++){46 if($(self._item[i])){47 $(self._item[i]).css('-webkit-transform','translateY('+(((i-self.idx)*_height)+_ofset)+'px');48 $(self._item[i]).css('-webkit-transition','none');49 }50 }/*"+(((i - self._idx) * width) + offsetX) + "px*/51 })52 this._item.on("touchend",function(e){53 if(self.offsetY==0){54 return false55 }56 console.log(self.offsetY)57 var offsetY=self.offsetY;58 /*if(offsetY==0){59 return false;60 }*/61 if(offsetY<0){62 self.starY("+1",e.type);63 }else{64 self.starY("-1",e.type);65 }66 }) 67 68 this._next && this._next.on("click",function(e){69 self.starY("+1",e.type);70 })71 this.prev && this.prev.on("click",function(e){72 self.starY("-1",e.type);73 })74 this.autoPlay && 75 setInterval(function(){76 self.starY("+1");77 },1000)78 79 },80 /*callback : function(){81 if(this.idx == 0){82 this._item[this.idx].siblings().hide();83 }84 },*/85 index : function(){86 return this.idx;87 },88 starY : function(num,type){89 var idx=this.idx,90 _width=this._width,91 _height=this._height,92 _item=this._item,93 len=_item.length;94 if(typeof(num)=="number"){95 nowIndex=idx+num;96 }97 if(typeof(num)=="string"){98 nowIndex=idx+num*1;99 }100 if(nowIndex>len-1) nowIndex=len-1;101 if(nowIndex<0) nowIndex=0;102 //console.log(nowIndex)103 $(_item[nowIndex]) && $(_item[nowIndex]).css('-webkit-transform','translate3d(0,0,0)');104 $(_item[nowIndex-1]) && $(_item[nowIndex-1]).css('-webkit-transform','translate3d(0,'+(-_height)+'px,0)');105 $(_item[nowIndex+1]) && $(_item[nowIndex+1]).css('-webkit-transform','translate3d(0,'+(_height)+'px,0)');106 $(_item[nowIndex]) && $(_item[nowIndex]).css('-webkit-transition','all 0.3s');107 $(_item[nowIndex-1]) && $(_item[nowIndex-1]).css('-webkit-transition','all 0.3s');108 $(_item[nowIndex+1]) && $(_item[nowIndex+1]).css('-webkit-transition','all 0.3s');109 110 this.idx=nowIndex;111 //console.log(type);112 if(type.indexOf(this.type)>=0){113 this.callback && this.callback()114 }115 //this._hua();116 }117 /*_hua : function(){118 var self = this;119 if(this.idx == 0){120 $(this._item[this.idx]).show().siblings().hide();121 }else if(this.idx == 1){122 $(this._item[this.idx]).show().siblings().hide();123 //self.local = true;124 }else if(this.idx == 2){125 $(this._item[this.idx]).show().siblings().hide();126 }else if(this.idx == 3){127 $(this._item[this.idx]).show().siblings().hide();128 }else if(this.idx == 4){129 $(this._item[this.idx]).show().siblings().hide();130 }else if(this.idx == 5){131 $(this._item[this.idx]).show().siblings().hide();132 }else if(this.idx == 6){133 $(this._item[this.idx]).show().siblings().hide();134 }else if(this.idx == 7){135 $(this._item[this.idx]).show().siblings().hide();136 }else if(this.idx == 8){137 $(this._item[this.idx]).show().siblings().hide();138 }139 }*/...

Full Screen

Full Screen

uploadedItem.js

Source:uploadedItem.js Github

copy

Full Screen

1// uploadedItem.js2import React from 'react'3import selectn from 'selectn'4import createReactClass from 'create-react-class'5import { setNewItem, removeItem } from './../../../../../actions/overviewActions'6import { YOUTUBE_EMBED_START, YOUTUBE_EMBED_END, YOUTUBE_URL, VIMEO_EMBED, VIMEO_URL } from './../../../International/constants'7export default createReactClass({8 _getImage(){9 let { item } = this.props,10 _item = {...item};11 _item.name = item.url.split('/').pop();12 _item.bg = {backgroundImage: 'url('+item.url+')'};13 return _item;14 },15 _getVideo(){16 let { item } = this.props,17 _item = {...item};18 if( _item.is_youtube === 1 ){19 _item.source = YOUTUBE_EMBED_START+_item.video_id+YOUTUBE_EMBED_END;20 _item.name = YOUTUBE_URL+_item.video_id;21 }else if( _item.is_youtube === 3 ){22 _item.source = VIMEO_EMBED+_item.video_id;23 _item.name = VIMEO_URL+_item.video_id;24 }25 return _item;26 },27 _isSelected(){28 let { dispatch, overview, item } = this.props,29 _item = item.is_youtube ? this._getVideo() : this._getImage(),30 new_item = _item.is_youtube ? 'new_vid' : 'new_img';31 return _item.id === selectn(new_item+'.id', overview) ? 'selected' : '';32 },33 render(){34 let { dispatch, item } = this.props,35 _item = item.is_youtube ? this._getVideo() : this._getImage(),36 isSelected = this._isSelected();37 return (38 <div className={"overview-item "+isSelected}>39 <div40 style={ _item.bg || {} }41 onClick={ () => dispatch( setNewItem(_item) ) }42 className="thumb">43 { _item.video_id && <iframe44 width="100%"45 height="100%"46 src={ _item.source }47 frameBorder="0"48 allowFullScreen /> }49 </div>50 <div51 onClick={ () => dispatch( setNewItem(_item) ) }52 className="name">53 { _item.name || '' }54 </div>55 <div className="remove">56 <div onClick={ () => dispatch( removeItem(_item) ) }>Remove</div>57 </div>58 </div>59 );60 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.pause()4 cy.contains('type').click()5 cy.url().should('include', '/commands/actions')6 cy.get('.action-email')7 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function () {2 it('Does not do much!', function () {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('fake@email')7 .should('have.value', 'fake@email')8 })9})10describe('My First Test', function () {11 it('Does not do much!', function () {12 cy.contains('type').click()13 cy.url().should('include', '/commands/actions')14 cy.get('.action-email')15 .type('fake@email')16 .should('have.value', 'fake@email')17 })18})19describe('My First Test', function () {20 it('Does not do much!', function () {21 cy.contains('type').click()22 cy.url().should('include', '/commands/actions')23 cy.get('.action-email')24 .type('fake@email')25 .should('have.value', 'fake@email')26 })27})28describe('My First Test', function () {29 it('Does not do much!', function () {30 cy.contains('type').click()31 cy.url().should('include', '/commands/actions')32 cy.get('.action-email')33 .type('fake@email')34 .should('have.value', 'fake@email')35 })36})37describe('My First Test', function () {38 it('Does not do much!', function () {39 cy.contains('type').click()40 cy.url().should('include',

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', () => {2 it('Does not do much!', () => {3 expect(true).to.equal(true)4 })5})6describe('My First Test', () => {7 it('Does not do much!', () => {8 expect(true).to.equal(true)9 })10})11describe('My First Test', () => {12 it('Does not do much!', () => {13 expect(true).to.equal(true)14 })15})16describe('My First Test', () => {17 it('Does not do much!', () => {18 expect(true).to.equal(true)19 })20})21describe('My First Test', () => {22 it('Does not do much!', () => {23 expect(true).to.equal(true)24 })25})26describe('My First Test', () => {27 it('Does not do much!', () => {28 expect(true).to.equal(true)29 })30})31describe('My First Test', () => {32 it('Does not do much!', () => {33 expect(true).to.equal(true)34 })35})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('_item', (selector, item) => {2 return cy.get(selector).eq(item)3})4Cypress.Commands.add('_item', (selector, item) => {5 return cy.get(selector).eq(item)6})7Cypress.Commands.add('_item', (selector, item) => {8 return cy.get(selector).eq(item)9})10Cypress.Commands.add('_item', (selector, item) => {11 return cy.get(selector).eq(item)12})13Cypress.Commands.add('_item', (selector, item) => {14 return cy.get(selector).eq(item)15})16Cypress.Commands.add('_item', (selector, item) => {17 return cy.get(selector).eq(item)18})19Cypress.Commands.add('_item', (selector, item) => {20 return cy.get(selector).eq(item)21})22Cypress.Commands.add('_item', (selector, item) => {23 return cy.get(selector).eq(item)24})25Cypress.Commands.add('_item', (selector, item) => {26 return cy.get(selector).eq(item)27})28Cypress.Commands.add('_item', (selector, item) => {29 return cy.get(selector).eq(item)30})31Cypress.Commands.add('_item', (selector, item) => {32 return cy.get(selector).eq(item)33})34Cypress.Commands.add('_item', (selector, item) => {35 return cy.get(selector).eq(item)36})37Cypress.Commands.add('_item', (selector, item) => {38 return cy.get(selector

Full Screen

Using AI Code Generation

copy

Full Screen

1import { _item } from "cypress/types/lodash";2describe('My First Test', function() {3 it('Does not do much!', function() {4 expect(true).to.equal(true)5 })6})7describe('My First Test', function() {8 it('Does not do much!', function() {9 expect(true).to.equal(true)10 })11})12describe('My First Test', function() {13 it('Does not do much!', function() {14 expect(true).to.equal(true)15 })16})17describe('My First Test', function() {18 it('Does not do much!', function() {19 expect(true).to.equal(true)20 })21})22describe('My First Test', function() {23 it('Does not do much!', function() {24 expect(true).to.equal(true)25 })26})27describe('My First Test', function() {28 it('Does not do much!', function() {29 expect(true).to.equal(true)30 })31})32describe('My First Test', function() {33 it('Does not do much!', function() {34 expect(true).to.equal(true)35 })36})37describe('My First Test', function() {38 it('Does not do much!', function() {39 expect(true).to.equal(true)40 })41})42describe('My First Test', function() {43 it('Does not do much!', function() {44 expect(true).to.equal(true)45 })46})47describe('My First Test', function() {48 it('Does not do much!', function() {49 expect(true).to.equal(true)50 })51})52describe('My First Test', function() {53 it('Does not do much!', function() {54 expect(true).to.equal(true)55 })56})57describe('My First Test', function() {58 it('Does not do much!', function() {59 expect(true).to.equal(true)60 })61})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.get('input').type('todos')4 cy.get('form').submit()5 cy.get('li').contains('todos')6 cy.get('li').contains('todos')._item(0).click()7 cy.get('li').contains('todos').should('have.class', 'completed')8 })9})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add("_item", (selector) => {2 if (selector.startsWith("#")) {3 return cy.get(selector);4 } else {5 return cy.get(`[data-cy=${selector}]`);6 }7});8Cypress.Commands.add("_click", (selector, options) => {9 cy._item(selector).click(options);10});11Cypress.Commands.add("_type", (selector, text, options) => {12 cy._item(selector).type(text, options);13});14Cypress.Commands.add("_clear", (selector, options) => {15 cy._item(selector).clear(options);16});17Cypress.Commands.add("_contains", (selector, content, options) => {18 cy._item(selector).contains(content, options);19});20Cypress.Commands.add("_should", (selector, assertion, value, options) => {21 cy._item(selector).should(assertion, value, options);22});23Cypress.Commands.add("_within", (selector, options, callback) => {24 cy._item(selector).within(options, callback);25});26Cypress.Commands.add("_each", (selector, callback) => {27 cy._item(selector).each(callback);28});29Cypress.Commands.add("_wait", (selector, options) => {30 cy._item(selector).wait(options);31});32Cypress.Commands.add("_invoke", (selector, method, ...args) => {33 cy._item(selector).invoke(method, ...args);34});35Cypress.Commands.add("_its", (selector, method) => {36 cy._item(selector).its(method);37});

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful