PageRenderTime 49ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/files/xe-core/1.7.5.7/common/js/xml_js_filter.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 431 lines | 317 code | 77 blank | 37 comment | 104 complexity | 230f47ed7c0d088d5ae3079956a6a514 MD5 | raw file
  1. /**
  2. * @file common/js/xml_js_filter.js
  3. * @author NAVER (developers@xpressengine.com)
  4. * @brief xml filter (validator) plugin
  5. *
  6. * A rule is a method validate one field.
  7. * A filter is made up of one or more rules.
  8. **/
  9. (function($){
  10. var messages = [];
  11. var rules = [];
  12. var filters = {};
  13. var callbacks = [];
  14. var extras = {};
  15. var Validator = xe.createApp('Validator', {
  16. init : function() {
  17. // {{{ add filters
  18. // email
  19. var regEmail = /^[\w-]+((?:\.|\+|\~)[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
  20. this.cast('ADD_RULE', ['email', regEmail]);
  21. this.cast('ADD_RULE', ['email_address', regEmail]);
  22. // userid
  23. var regUserid = /^[a-z]+[\w-]*[a-z0-9_]+$/i;
  24. this.cast('ADD_RULE', ['userid', regUserid]);
  25. this.cast('ADD_RULE', ['user_id', regUserid]);
  26. // url
  27. var regUrl = /^(https?|ftp|mms):\/\/[0-9a-z-]+(\.[_0-9a-z-]+)+(:\d+)?/;
  28. this.cast('ADD_RULE', ['url', regUrl]);
  29. this.cast('ADD_RULE', ['homepage', regUrl]);
  30. // korean
  31. var regKor = new RegExp('^[\uAC00-\uD7A3]*$');
  32. this.cast('ADD_RULE', ['korean', regKor]);
  33. // korean_number
  34. var regKorNum = new RegExp('^[\uAC00-\uD7A30-9]*$');
  35. this.cast('ADD_RULE', ['korean_number', regKorNum]);
  36. // alpha
  37. var regAlpha = /^[a-z]*$/i;
  38. this.cast('ADD_RULE', ['alpha', regAlpha]);
  39. // alpha_number
  40. var regAlphaNum = /^[a-z][a-z0-9_]*$/i;
  41. this.cast('ADD_RULE', ['alpha_number', regAlphaNum]);
  42. // number
  43. var regNum = /^[0-9]*$/;
  44. this.cast('ADD_RULE', ['number', regNum]);
  45. // }}} add filters
  46. },
  47. // run validator
  48. run : function(oForm) {
  49. var filter = '';
  50. if (oForm._filter) filter = oForm._filter.value;
  51. var params = [oForm, filter];
  52. var result = this.cast('VALIDATE', params);
  53. if (typeof result == 'undefined') result = false;
  54. return result;
  55. },
  56. API_ONREADY : function() {
  57. var self = this;
  58. // hook form submit event
  59. $('form')
  60. .each(function(){
  61. if (this.onsubmit) {
  62. this['xe:onsubmit'] = this.onsubmit;
  63. this.onsubmit = null;
  64. }
  65. })
  66. .submit(function(e){
  67. var legacyFn = this['xe:onsubmit'];
  68. var hasLegacyFn = $.isFunction(legacyFn);
  69. var bResult = hasLegacyFn?legacyFn.apply(this):self.run(this);
  70. if(!bResult)
  71. {
  72. e.stopImmediatePropagation();
  73. }
  74. return bResult;
  75. });
  76. },
  77. API_VALIDATE : function(sender, params) {
  78. var result = true, form = params[0], elems = form.elements, filter, filter_to_add, ruleset, callback;
  79. var fields, names, name, el, val, mod, len, lenb, max, min, maxb, minb, rules, e_el, e_val, i, c, r, if_, fn;
  80. if(elems.ruleset) {
  81. filter = form.elements.ruleset.value;
  82. } else if(elems._filter) {
  83. filter = form.elements._filter.value;
  84. }
  85. if(!filter) return true;
  86. if($.isFunction(callbacks[filter])) callback = callbacks[filter];
  87. filter = $.extend({}, filters[filter.toLowerCase()] || {}, extras);
  88. function regex_quote(str) {
  89. return str.replace(/([\.\+\-\[\]\{\}\(\)\\])/g, '\\$1');
  90. }
  91. // get form names
  92. fields = [];
  93. for(i=0,c=form.elements.length; i < c; i++) {
  94. el = elems[i];
  95. name = el.name;
  96. if(!name || !elems[name]) continue;
  97. if(!elems[name].length || elems[name][0] === el) fields.push(name);
  98. }
  99. fields = fields.join('\n');
  100. // get field names matching patterns
  101. filter_to_add = {};
  102. for(name in filter) {
  103. if(!filter.hasOwnProperty(name)) continue;
  104. names = [];
  105. if(name.substr(0,1) == '^') {
  106. names = fields.match( (new RegExp('^'+regex_quote(name.substr(1))+'.*$','gm')) );
  107. } else {
  108. continue;
  109. }
  110. if(!names) names = [];
  111. for(i=0,c=names.length; i < c; i++) {
  112. filter_to_add[names[i]]= filter[name];
  113. }
  114. filter[name] = null;
  115. delete filter[name];
  116. }
  117. filter = $.extend(filter, filter_to_add);
  118. for(name in filter) {
  119. if(!filter.hasOwnProperty(name)) continue;
  120. f = filter[name];
  121. el = elems[name];
  122. if(!el)
  123. {
  124. el = elems[name + '[]'];
  125. }
  126. val = el?$.trim(get_value($(el))):'';
  127. mod = (f.modifier||'')+',';
  128. if(!el || el.disabled) continue;
  129. if(f['if']) {
  130. if(!$.isArray(f['if'])) f['if'] = [f['if']];
  131. for(i=0;i<f['if'].length;i++) {
  132. /*jslint evil: true */
  133. if_ = f['if'][i];
  134. fn = new Function('el', 'return !!(' + (if_.test.replace(/\$(\w+)/g, '(jQuery(\'[name=$1]\').is(\':radio, :checkbox\') ? jQuery(\'[name=$1]:checked\').val() : jQuery(\'[name=$1]\').val())')) +')');
  135. //fn = new Function('el', 'return !!(' + (if_.test.replace(/\$(\w+)/g, 'el["$1"].value')) +')');
  136. if(fn(elems)) f[if_.attr] = if_.value;
  137. else delete f[if_.attr];
  138. }
  139. }
  140. if(!val) {
  141. if(f['default']) val = f['default'];
  142. if(f.required) return this.cast('ALERT', [form, name, 'isnull']) && false;
  143. else continue;
  144. }
  145. min = parseInt(f.minlength) || 0;
  146. max = parseInt(f.maxlength) || 0;
  147. minb = /b$/.test(f.minlength||'');
  148. maxb = /b$/.test(f.maxlength||'');
  149. len = val.length;
  150. if(minb || maxb) lenb = get_bytes(val);
  151. if((min && min > (minb?lenb:len)) || (max && max < (maxb?lenb:len))) {
  152. return this.cast('ALERT', [form, name, 'outofrange', min, max]) && false;
  153. }
  154. if(f.equalto) {
  155. e_el = elems[f.equalto];
  156. e_val = e_el?$.trim(get_value($(e_el))):'';
  157. if(e_el && e_val !== val) {
  158. return this.cast('ALERT', [form, name, 'equalto']) && false;
  159. }
  160. }
  161. rules = (f.rule || '').split(',');
  162. for(i=0,c=rules.length; i < c; i++) {
  163. if(!(r = rules[i])) continue;
  164. result = this.cast('APPLY_RULE', [r, val]);
  165. if(mod.indexOf('not,') > -1) result = !result;
  166. if(!result) {
  167. return this.cast('ALERT', [form, name, 'invalid_'+r]) && false;
  168. }
  169. }
  170. }
  171. if($.isFunction(callback)) return callback(form);
  172. return true;
  173. },
  174. API_ADD_RULE : function(sender, params) {
  175. var name = params[0].toLowerCase();
  176. rules[name] = params[1];
  177. },
  178. API_DEL_RULE : function(sender, params) {
  179. var name = params[0].toLowerCase();
  180. delete rules[name];
  181. },
  182. API_GET_RULE : function(sender, params) {
  183. var name = params[0].toLowerCase();
  184. if (rules[name]) {
  185. return rules[name];
  186. } else {
  187. return null;
  188. }
  189. },
  190. API_ADD_FILTER : function(sender, params) {
  191. var name = params[0].toLowerCase();
  192. var filter = params[1];
  193. filters[name] = filter;
  194. },
  195. API_DEL_FILTER : function(sender, params) {
  196. var name = params[0].toLowerCase();
  197. delete filters[name];
  198. },
  199. API_GET_FILTER : function(sender, params) {
  200. var name = params[0].toLowerCase();
  201. if (filters[name]) {
  202. return filters[name];
  203. } else {
  204. return null;
  205. }
  206. },
  207. API_ADD_EXTRA_FIELD : function(sender, params) {
  208. var name = params[0].toLowerCase();
  209. var prop = params[1];
  210. extras[name] = prop;
  211. },
  212. API_GET_EXTRA_FIELD : function(sender, params) {
  213. var name = params[0].toLowerCase();
  214. return extras[name];
  215. },
  216. API_DEL_EXTRA_FIELD : function(sender, params) {
  217. var name = params[0].toLowerCase();
  218. delete extras[name];
  219. },
  220. API_APPLY_RULE : function(sender, params) {
  221. var name = params[0];
  222. var value = params[1];
  223. if(typeof(rules[name]) == 'undefined') return true; // no filter
  224. if($.isFunction(rules[name])) return rules[name](value);
  225. if(rules[name] instanceof RegExp) return rules[name].test(value);
  226. if($.isArray(rules[name])) return ($.inArray(value, rules[name]) > -1);
  227. return true;
  228. },
  229. API_ALERT : function(sender, params) {
  230. var form = params[0];
  231. var field_name = params[1];
  232. var msg_code = params[2];
  233. var minlen = params[3];
  234. var maxlen = params[4];
  235. var field_msg = this.cast('GET_MESSAGE', [field_name]);
  236. var msg = this.cast('GET_MESSAGE', [msg_code]);
  237. if (msg != msg_code) msg = (msg.indexOf('%s')<0)?(field_msg+msg):(msg.replace('%s',field_msg));
  238. if (minlen||maxlen) msg += '('+(minlen||'')+'~'+(maxlen||'')+')';
  239. this.cast('SHOW_ALERT', [msg]);
  240. // set focus
  241. $(form.elements[field_name]).focus();
  242. },
  243. API_SHOW_ALERT : function(sender, params) {
  244. alert(params[0]);
  245. },
  246. API_ADD_MESSAGE : function(sender, params) {
  247. var msg_code = params[0];
  248. var msg_str = params[1];
  249. messages[msg_code] = msg_str;
  250. },
  251. API_GET_MESSAGE : function(sender, params) {
  252. var msg_code = params[0];
  253. return messages[msg_code] || msg_code;
  254. },
  255. API_ADD_CALLBACK : function(sender, params) {
  256. var name = params[0];
  257. var func = params[1];
  258. callbacks[name] = func;
  259. },
  260. API_REMOVE_CALLBACK : function(sender, params) {
  261. var name = params[0];
  262. delete callbacks[name];
  263. }
  264. });
  265. var oValidator = new Validator();
  266. // register validator
  267. xe.registerApp(oValidator);
  268. // 호환성을 위해 추가한 플러그인 - 에디터에서 컨텐트를 가져와서 설정한다.
  269. var EditorStub = xe.createPlugin('editor_stub', {
  270. API_BEFORE_VALIDATE : function(sender, params) {
  271. var form = params[0];
  272. var seq = form.getAttribute('editor_sequence');
  273. // bug fix for IE6,7
  274. if (seq && typeof seq == 'object') seq = seq.value;
  275. if (seq) {
  276. try {
  277. editorRelKeys[seq].content.value = editorRelKeys[seq].func(seq) || '';
  278. } catch(e) { }
  279. }
  280. }
  281. });
  282. oValidator.registerPlugin(new EditorStub());
  283. // functions
  284. function get_value($elem) {
  285. var vals = [];
  286. if ($elem.is(':radio')){
  287. return $elem.filter(':checked').val();
  288. } else if ($elem.is(':checkbox')) {
  289. $elem.filter(':checked').each(function(){
  290. vals.push(this.value);
  291. });
  292. return vals.join('|@|');
  293. } else {
  294. return $elem.val();
  295. }
  296. }
  297. function get_bytes(str) {
  298. str += '';
  299. if(!str.length) return 0;
  300. str = encodeURI(str);
  301. var c = str.split('%').length - 1;
  302. return str.length - c*2;
  303. }
  304. })(jQuery);
  305. /**
  306. * @function filterAlertMessage
  307. * @brief ajax로 서버에 요청후 결과를 처리할 callback_function을 지정하지 않았을 시 호출되는 기본 함수
  308. **/
  309. function filterAlertMessage(ret_obj) {
  310. var error = ret_obj.error;
  311. var message = ret_obj.message;
  312. var act = ret_obj.act;
  313. var redirect_url = ret_obj.redirect_url;
  314. var url = location.href;
  315. if(typeof(message) != "undefined" && message && message != "success") alert(message);
  316. if(typeof(act)!="undefined" && act) url = current_url.setQuery("act", act);
  317. else if(typeof(redirect_url) != "undefined" && redirect_url) url = redirect_url;
  318. if(url == location.href) url = url.replace(/#(.*)$/,'');
  319. location.href = url;
  320. }
  321. /**
  322. * @brief Function to process filters
  323. * @deprecated
  324. */
  325. function procFilter(form, filter_func) {
  326. filter_func(form);
  327. return false;
  328. }
  329. function legacy_filter(filter_name, form, module, act, callback, responses, confirm_msg, rename_params) {
  330. var v = xe.getApp('Validator')[0], $ = jQuery, args = [];
  331. if (!v) return false;
  332. if (!form.elements._filter) $(form).prepend('<input type="hidden" name="_filter" />');
  333. form.elements._filter.value = filter_name;
  334. args[0] = filter_name;
  335. args[1] = function(f) {
  336. var params = {}, res = [], elms = f.elements, data = $(f).serializeArray();
  337. $.each(data, function(i, field) {
  338. var v = $.trim(field.value), n = field.name;
  339. if(!v || !n) return true;
  340. if(rename_params[n]) n = rename_params[n];
  341. if(/\[\]$/.test(n)) n = n.replace(/\[\]$/, '');
  342. if(params[n]) {
  343. params[n] += '|@|'+v;
  344. } else {
  345. params[n] = field.value;
  346. }
  347. });
  348. if (confirm_msg && !confirm(confirm_msg)) return false;
  349. exec_xml(module, act, params, callback, responses, params, form);
  350. };
  351. v.cast('ADD_CALLBACK', args);
  352. v.cast('VALIDATE', [form, filter_name]);
  353. return false;
  354. }