PageRenderTime 5939ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/common/js/src/xml_js_filter.js

http://xe-core.googlecode.com/
JavaScript | 338 lines | 245 code | 60 blank | 33 comment | 71 complexity | c49307ec97244152ada411fac1220948 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause
  1. /**
  2. * @file common/js/xml_js_filter.js
  3. * @author NHN (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-\/\~]+)+(:[0-9]{2,4})*$/;
  28. this.cast('ADD_RULE', ['url', regUrl]);
  29. this.cast('ADD_RULE', ['homepage', regUrl]);
  30. // korean
  31. var regKor = /^[-]*$/;
  32. this.cast('ADD_RULE', ['korean', regKor]);
  33. // korean_number
  34. var regKorNum = /^[-힣0-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(){
  67. var legacyFn = this['xe:onsubmit'];
  68. var hasLegacyFn = $.isFunction(legacyFn);
  69. var bResult = hasLegacyFn?legacyFn.apply(this):self.run(this);
  70. return bResult;
  71. });
  72. },
  73. API_VALIDATE : function(sender, params) {
  74. var self = this, result = true, form = params[0], filter=null, callback=null;
  75. if (form.elements['_filter']) filter = form.elements['_filter'].value;
  76. if (!filter) return true;
  77. if ($.isFunction(callbacks[filter])) callback = callbacks[filter];
  78. filter = $.extend({}, filters[filter.toLowerCase()] || {}, extras);
  79. $.each(filter, function(name) {
  80. var _el = form.elements[name];
  81. if (!_el) return true;
  82. var el = $(_el), val = $.trim(get_value(el));
  83. var minlen = parseInt(this.minlength) || 0;
  84. var maxlen = parseInt(this.maxlength) || 0;
  85. var rule = (this.rule || '').split(',');
  86. if (this.required && !val) return (result = (!!self.cast('ALERT', [form, name, 'isnull']) && false));
  87. if (!this.required && !val) return (result = true);
  88. if ((minlen && val.length < minlen) || (maxlen && val.length > maxlen)) return (result = (!!self.cast('ALERT', [form, name, 'outofrange', minlen, maxlen]) && false));
  89. if (this.equalto) {
  90. var eq_val = get_value($(form.elements[this.equalto]));
  91. if (eq_val != val) return (result = (!!self.cast('ALERT', [form, name, 'equalto']) && false));
  92. }
  93. if (rule) {
  94. $.each(rule, function(i,r) {
  95. if (!r) return true;
  96. var ret = self.cast('APPLY_RULE', [r, val]);
  97. if (!ret) {
  98. self.cast('ALERT', [form, name, 'invalid_'+this]);
  99. return (result = false);
  100. }
  101. });
  102. }
  103. if (!result) return false;
  104. });
  105. if (!result) return false;
  106. if ($.isFunction(callback)) return callback(form);
  107. return true;
  108. },
  109. API_ADD_RULE : function(sender, params) {
  110. var name = params[0].toLowerCase();
  111. rules[name] = params[1];
  112. },
  113. API_DEL_RULE : function(sender, params) {
  114. var name = params[0].toLowerCase();
  115. delete rules[name];
  116. },
  117. API_GET_RULE : function(sender, params) {
  118. var name = params[0].toLowerCase();
  119. if (rules[name]) {
  120. return rules[name];
  121. } else {
  122. return null;
  123. }
  124. },
  125. API_ADD_FILTER : function(sender, params) {
  126. var name = params[0].toLowerCase();
  127. var filter = params[1];
  128. filters[name] = filter;
  129. },
  130. API_DEL_FILTER : function(sender, params) {
  131. var name = params[0].toLowerCase();
  132. delete filters[name];
  133. },
  134. API_GET_FILTER : function(sender, params) {
  135. var name = params[0].toLowerCase();
  136. if (filters[name]) {
  137. return filters[name];
  138. } else {
  139. return null;
  140. }
  141. },
  142. API_ADD_EXTRA_FIELD : function(sender, params) {
  143. var name = params[0].toLowerCase();
  144. var prop = params[1];
  145. extras[name] = prop;
  146. },
  147. API_GET_EXTRA_FIELD : function(sender, params) {
  148. var name = params[0].toLowerCase();
  149. return extras[name];
  150. },
  151. API_DEL_EXTRA_FIELD : function(sender, params) {
  152. var name = params[0].toLowerCase();
  153. delete extras[name];
  154. },
  155. API_APPLY_RULE : function(sender, params) {
  156. var name = params[0];
  157. var value = params[1];
  158. if (typeof(rules[name]) == 'undefined') return true; // no filter
  159. if ($.isFunction(rules[name])) return rules[name](value);
  160. if (rules[name] instanceof RegExp) return rules[name].test(value);
  161. return true;
  162. },
  163. API_ALERT : function(sender, params) {
  164. var form = params[0];
  165. var field_name = params[1];
  166. var msg_code = params[2];
  167. var minlen = params[3];
  168. var maxlen = params[4];
  169. var field_msg = this.cast('GET_MESSAGE', [field_name]);
  170. var msg = this.cast('GET_MESSAGE', [msg_code]);
  171. if (msg != msg_code) msg = (msg.indexOf('%s')<0)?(field_msg+msg):(msg.replace('%s',field_msg));
  172. if (minlen||maxlen) msg += '('+(minlen||'')+'~'+(maxlen||'')+')';
  173. this.cast('SHOW_ALERT', [msg]);
  174. // set focus
  175. $(form.elements[field_name]).focus();
  176. },
  177. API_SHOW_ALERT : function(sender, params) {
  178. alert(params[0]);
  179. },
  180. API_ADD_MESSAGE : function(sender, params) {
  181. var msg_code = params[0];
  182. var msg_str = params[1];
  183. messages[msg_code] = msg_str;
  184. },
  185. API_GET_MESSAGE : function(sender, params) {
  186. var msg_code = params[0];
  187. return messages[msg_code] || msg_code;
  188. },
  189. API_ADD_CALLBACK : function(sender, params) {
  190. var name = params[0];
  191. var func = params[1];
  192. callbacks[name] = func;
  193. },
  194. API_REMOVE_CALLBACK : function(sender, params) {
  195. var name = params[0];
  196. delete callbacks[name];
  197. }
  198. });
  199. var oValidator = new Validator;
  200. // register validator
  201. xe.registerApp(oValidator);
  202. // 호환성을 위해 추가한 플러그인 - 에디터에서 컨텐트를 가져와서 설정한다.
  203. var EditorStub = xe.createPlugin('editor_stub', {
  204. API_BEFORE_VALIDATE : function(sender, params) {
  205. var form = params[0];
  206. var seq = form.getAttribute('editor_sequence');
  207. // bug fix for IE6,7
  208. if (seq && typeof seq == 'object') seq = seq.value;
  209. if (seq) {
  210. try {
  211. editorRelKeys[seq].content.value = editorRelKeys[seq].func(seq) || '';
  212. } catch(e) { }
  213. }
  214. }
  215. });
  216. oValidator.registerPlugin(new EditorStub);
  217. // functions
  218. function get_value(elem) {
  219. var vals = [];
  220. if (elem.is(':radio')){
  221. return elem.filter(':checked').val();
  222. } else if (elem.is(':checkbox')) {
  223. elem.filter(':checked').each(function(){
  224. vals.push(this.value);
  225. });
  226. return vals.join('|@|');
  227. } else {
  228. return elem.val();
  229. }
  230. }
  231. })(jQuery);
  232. /**
  233. * @function filterAlertMessage
  234. * @brief ajax로 서버에 요청후 결과를 처리할 callback_function을 지정하지 않았을 시 호출되는 기본 함수
  235. **/
  236. function filterAlertMessage(ret_obj) {
  237. var error = ret_obj["error"];
  238. var message = ret_obj["message"];
  239. var act = ret_obj["act"];
  240. var redirect_url = ret_obj["redirect_url"];
  241. var url = location.href;
  242. if(typeof(message)!="undefined"&&message&&message!="success") alert(message);
  243. if(typeof(act)!="undefined" && act) url = current_url.setQuery("act", act);
  244. else if(typeof(redirect_url)!="undefined" && redirect_url) url = redirect_url;
  245. if(url == location.href) url = url.replace(/#(.*)$/,'');
  246. location.href = url;
  247. }
  248. /**
  249. * @brief Function to process filters
  250. * @deprecated
  251. */
  252. function procFilter(form, filter_func) {
  253. filter_func(form);
  254. return false;
  255. }
  256. function legacy_filter(filter_name, form, module, act, callback, responses, confirm_msg, rename_params) {
  257. var v = xe.getApp('Validator')[0], $ = jQuery, args = [];
  258. if (!v) return false;
  259. if (!form.elements['_filter']) $(form).prepend('<input type="hidden" name="_filter" />');
  260. form.elements['_filter'].value = filter_name;
  261. args[0] = filter_name;
  262. args[1] = function(f) {
  263. var params = {}, res = [], elms = f.elements, data = $(f).serializeArray();
  264. $.each(data, function(i, field) {
  265. var v = $.trim(field.value), n = field.name;
  266. if(!v || !n) return true;
  267. if(rename_params[n]) n = rename_params[n];
  268. if(/\[\]$/.test(n)) n = n.replace(/\[\]$/, '');
  269. if(params[n]) params[n] += '|@|'+v;
  270. else params[n] = field.value;
  271. });
  272. if (confirm_msg && !confirm(confirm_msg)) return false;
  273. exec_xml(module, act, params, callback, responses, params, form);
  274. };
  275. v.cast('ADD_CALLBACK', args);
  276. v.cast('VALIDATE', [form, filter_name]);
  277. return false;
  278. }