require-form.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. define(['jquery', 'bootstrap', 'upload', 'validator', 'validator-lang'], function ($, undefined, Upload, Validator, undefined) {
  2. var Form = {
  3. config: {
  4. fieldlisttpl: '<dd class="form-inline"><input type="text" name="<%=name%>[<%=index%>][key]" class="form-control" value="<%=key%>" placeholder="<%=options.keyPlaceholder||\'\'%>" size="10" /> <input type="text" name="<%=name%>[<%=index%>][value]" class="form-control" value="<%=value%>" placeholder="<%=options.valuePlaceholder||\'\'%>" /> <span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span> <span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span></dd>'
  5. },
  6. events: {
  7. validator: function (form, success, error, submit) {
  8. if (!form.is("form"))
  9. return;
  10. //绑定表单事件
  11. form.validator($.extend({
  12. rules: {
  13. username: [/^\w{3,30}$/, __('Username must be 3 to 30 characters')],
  14. password: [/^[\S]{6,30}$/, __('Password must be 6 to 30 characters')]
  15. },
  16. validClass: 'has-success',
  17. invalidClass: 'has-error',
  18. bindClassTo: '.form-group',
  19. formClass: 'n-default n-bootstrap',
  20. msgClass: 'n-right',
  21. stopOnError: true,
  22. display: function (elem) {
  23. return $(elem).closest('.form-group').find(".control-label").text().replace(/\:/, '');
  24. },
  25. dataFilter: function (data) {
  26. if (data.code === 1) {
  27. return data.msg ? {"ok": data.msg} : '';
  28. } else {
  29. return data.msg;
  30. }
  31. },
  32. target: function (input) {
  33. var target = $(input).data("target");
  34. if (target && $(target).length > 0) {
  35. return $(target);
  36. }
  37. var $formitem = $(input).closest('.form-group'),
  38. $msgbox = $formitem.find('span.msg-box');
  39. if (!$msgbox.length) {
  40. return [];
  41. }
  42. return $msgbox;
  43. },
  44. valid: function (ret) {
  45. var that = this, submitBtn = $(".layer-footer [type=submit]", form);
  46. that.holdSubmit(true);
  47. submitBtn.addClass("disabled");
  48. //验证通过提交表单
  49. var submitResult = Form.api.submit($(ret), function (data, ret) {
  50. that.holdSubmit(false);
  51. submitBtn.removeClass("disabled");
  52. if (false === $(this).triggerHandler("success.form", [data, ret])) {
  53. return false;
  54. }
  55. if (typeof success === 'function') {
  56. if (false === success.call($(this), data, ret)) {
  57. return false;
  58. }
  59. }
  60. //提示及关闭当前窗口
  61. var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
  62. parent.Toastr.success(msg);
  63. parent.$(".btn-refresh").trigger("click");
  64. if (window.name) {
  65. var index = parent.Layer.getFrameIndex(window.name);
  66. parent.Layer.close(index);
  67. }
  68. return false;
  69. }, function (data, ret) {
  70. that.holdSubmit(false);
  71. if (false === $(this).triggerHandler("error.form", [data, ret])) {
  72. return false;
  73. }
  74. submitBtn.removeClass("disabled");
  75. if (typeof error === 'function') {
  76. if (false === error.call($(this), data, ret)) {
  77. return false;
  78. }
  79. }
  80. }, submit);
  81. //如果提交失败则释放锁定
  82. if (!submitResult) {
  83. that.holdSubmit(false);
  84. submitBtn.removeClass("disabled");
  85. }
  86. return false;
  87. }
  88. }, form.data("validator-options") || {}));
  89. //移除提交按钮的disabled类
  90. $(".layer-footer [type=submit],.fixed-footer [type=submit],.normal-footer [type=submit]", form).removeClass("disabled");
  91. //自定义关闭按钮事件
  92. form.on("click", ".layer-close", function () {
  93. if (window.name) {
  94. var index = parent.Layer.getFrameIndex(window.name);
  95. parent.Layer.close(index);
  96. }
  97. return false;
  98. });
  99. },
  100. selectpicker: function (form) {
  101. //绑定select元素事件
  102. if ($(".selectpicker", form).length > 0) {
  103. require(['bootstrap-select', 'bootstrap-select-lang'], function () {
  104. $.fn.selectpicker.Constructor.BootstrapVersion = '3';
  105. $('.selectpicker', form).selectpicker();
  106. $(form).on("reset", function () {
  107. setTimeout(function () {
  108. $('.selectpicker').selectpicker('refresh').trigger("change");
  109. }, 1);
  110. });
  111. });
  112. }
  113. },
  114. selectpage: function (form) {
  115. //绑定selectpage元素事件
  116. if ($(".selectpage", form).length > 0) {
  117. require(['selectpage'], function () {
  118. $('.selectpage', form).selectPage({
  119. eAjaxSuccess: function (data) {
  120. data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
  121. data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
  122. return data;
  123. }
  124. });
  125. });
  126. //给隐藏的元素添加上validate验证触发事件
  127. $(document).on("change", ".sp_hidden", function () {
  128. $(this).trigger("validate");
  129. });
  130. $(document).on("change", ".sp_input", function () {
  131. $(this).closest(".sp_container").find(".sp_hidden").trigger("change");
  132. });
  133. $(form).on("reset", function () {
  134. setTimeout(function () {
  135. $(".selectpage", form).each(function () {
  136. var selectpage = $(this).data("selectPageObject");
  137. selectpage.elem.hidden.val($(this).val());
  138. $(this).selectPageRefresh();
  139. });
  140. }, 1);
  141. });
  142. }
  143. },
  144. cxselect: function (form) {
  145. //绑定cxselect元素事件
  146. if ($("[data-toggle='cxselect']", form).length > 0) {
  147. require(['cxselect'], function () {
  148. $.cxSelect.defaults.jsonName = 'name';
  149. $.cxSelect.defaults.jsonValue = 'value';
  150. $.cxSelect.defaults.jsonSpace = 'data';
  151. $("[data-toggle='cxselect']", form).cxSelect();
  152. });
  153. }
  154. },
  155. citypicker: function (form) {
  156. //绑定城市远程插件
  157. if ($("[data-toggle='city-picker']", form).length > 0) {
  158. require(['citypicker'], function () {
  159. $(form).on("reset", function () {
  160. setTimeout(function () {
  161. $("[data-toggle='city-picker']").citypicker('refresh');
  162. }, 1);
  163. });
  164. });
  165. }
  166. },
  167. datetimepicker: function (form) {
  168. //绑定日期时间元素事件
  169. if ($(".datetimepicker", form).length > 0) {
  170. require(['bootstrap-datetimepicker'], function () {
  171. var options = {
  172. format: 'YYYY-MM-DD HH:mm:ss',
  173. icons: {
  174. time: 'fa fa-clock-o',
  175. date: 'fa fa-calendar',
  176. up: 'fa fa-chevron-up',
  177. down: 'fa fa-chevron-down',
  178. previous: 'fa fa-chevron-left',
  179. next: 'fa fa-chevron-right',
  180. today: 'fa fa-history',
  181. clear: 'fa fa-trash',
  182. close: 'fa fa-remove'
  183. },
  184. showTodayButton: true,
  185. showClose: true
  186. };
  187. $('.datetimepicker', form).parent().css('position', 'relative');
  188. $('.datetimepicker', form).datetimepicker(options).on('dp.change', function (e) {
  189. $(this, document).trigger("changed");
  190. });
  191. });
  192. }
  193. },
  194. daterangepicker: function (form) {
  195. //绑定日期时间元素事件
  196. if ($(".datetimerange", form).length > 0) {
  197. require(['bootstrap-daterangepicker'], function () {
  198. var ranges = {};
  199. ranges[__('Today')] = [Moment().startOf('day'), Moment().endOf('day')];
  200. ranges[__('Yesterday')] = [Moment().subtract(1, 'days').startOf('day'), Moment().subtract(1, 'days').endOf('day')];
  201. ranges[__('Last 7 Days')] = [Moment().subtract(6, 'days').startOf('day'), Moment().endOf('day')];
  202. ranges[__('Last 30 Days')] = [Moment().subtract(29, 'days').startOf('day'), Moment().endOf('day')];
  203. ranges[__('This Month')] = [Moment().startOf('month'), Moment().endOf('month')];
  204. ranges[__('Last Month')] = [Moment().subtract(1, 'month').startOf('month'), Moment().subtract(1, 'month').endOf('month')];
  205. var options = {
  206. timePicker: false,
  207. autoUpdateInput: false,
  208. timePickerSeconds: true,
  209. timePicker24Hour: true,
  210. autoApply: true,
  211. locale: {
  212. format: 'YYYY-MM-DD HH:mm:ss',
  213. customRangeLabel: __("Custom Range"),
  214. applyLabel: __("Apply"),
  215. cancelLabel: __("Clear"),
  216. },
  217. ranges: ranges,
  218. };
  219. var origincallback = function (start, end) {
  220. $(this.element).val(start.format(this.locale.format) + " - " + end.format(this.locale.format));
  221. $(this.element).trigger('change').trigger('validate');
  222. };
  223. $(".datetimerange", form).each(function () {
  224. var callback = typeof $(this).data('callback') == 'function' ? $(this).data('callback') : origincallback;
  225. $(this).on('apply.daterangepicker', function (ev, picker) {
  226. callback.call(picker, picker.startDate, picker.endDate);
  227. });
  228. $(this).on('cancel.daterangepicker', function (ev, picker) {
  229. $(this).val('').trigger('change').trigger('validate');
  230. });
  231. $(this).daterangepicker($.extend(true, {}, options, $(this).data() || {}, $(this).data("daterangepicker-options") || {}));
  232. });
  233. });
  234. }
  235. },
  236. /**
  237. * 绑定上传事件
  238. * @param form
  239. * @deprecated Use faupload instead.
  240. */
  241. plupload: function (form) {
  242. Form.events.faupload(form);
  243. },
  244. /**
  245. * 绑定上传事件
  246. * @param form
  247. */
  248. faupload: function (form) {
  249. //绑定上传元素事件
  250. if ($(".plupload,.faupload", form).length > 0) {
  251. Upload.api.upload($(".plupload,.faupload", form));
  252. }
  253. },
  254. faselect: function (form) {
  255. //绑定fachoose选择附件事件
  256. if ($(".faselect,.fachoose", form).length > 0) {
  257. $(".faselect,.fachoose", form).off('click').on('click', function () {
  258. var that = this;
  259. var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
  260. var mimetype = $(this).data("mimetype") ? $(this).data("mimetype") : '';
  261. var admin_id = $(this).data("admin-id") ? $(this).data("admin-id") : '';
  262. var user_id = $(this).data("user-id") ? $(this).data("user-id") : '';
  263. mimetype = mimetype.replace(/\/\*/ig, '/');
  264. var url = $(this).data("url") ? $(this).data("url") : (typeof Backend !== 'undefined' ? "general/attachment/select" : "user/attachment");
  265. parent.Fast.api.open(url + "?element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype=" + mimetype + "&admin_id=" + admin_id + "&user_id=" + user_id, __('Choose'), {
  266. callback: function (data) {
  267. var button = $(that);
  268. var maxcount = $(button).data("maxcount");
  269. var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
  270. maxcount = typeof maxcount !== "undefined" ? maxcount : 0;
  271. if (input_id && data.multiple) {
  272. var urlArr = [];
  273. var inputObj = $("#" + input_id);
  274. var value = $.trim(inputObj.val());
  275. if (value !== "") {
  276. urlArr.push(inputObj.val());
  277. }
  278. var nums = value === '' ? 0 : value.split(/\,/).length;
  279. var files = data.url !== "" ? data.url.split(/\,/) : [];
  280. $.each(files, function (i, j) {
  281. var url = Config.upload.fullmode ? Fast.api.cdnurl(j) : j;
  282. urlArr.push(url);
  283. });
  284. if (maxcount > 0) {
  285. var remains = maxcount - nums;
  286. if (files.length > remains) {
  287. Toastr.error(__('You can choose up to %d file%s', remains));
  288. return false;
  289. }
  290. }
  291. var result = urlArr.join(",");
  292. inputObj.val(result).trigger("change").trigger("validate");
  293. } else if (input_id) {
  294. var url = Config.upload.fullmode ? Fast.api.cdnurl(data.url) : data.url;
  295. $("#" + input_id).val(url).trigger("change").trigger("validate");
  296. }
  297. // 触发选择文件自定义事件
  298. button.trigger("fa.event.selectedfile", data);
  299. }
  300. });
  301. return false;
  302. });
  303. }
  304. },
  305. fieldlist: function (form) {
  306. //绑定fieldlist
  307. if ($(".fieldlist", form).length > 0) {
  308. require(['dragsort', 'template'], function (undefined, Template) {
  309. //刷新隐藏textarea的值
  310. var refresh = function (container) {
  311. var data = {};
  312. var name = container.data("name");
  313. var textarea = $("textarea[name='" + name + "']", form);
  314. var template = container.data("template");
  315. $.each($("input,select,textarea", container).serializeArray(), function (i, j) {
  316. var reg = /\[(\w+)\]\[(\w+)\]$/g;
  317. var match = reg.exec(j.name);
  318. if (!match)
  319. return true;
  320. match[1] = "x" + parseInt(match[1]);
  321. if (typeof data[match[1]] == 'undefined') {
  322. data[match[1]] = {};
  323. }
  324. data[match[1]][match[2]] = j.value;
  325. });
  326. //使用数组保存
  327. var usearray = container.data("usearray") || false;
  328. //保留空数据
  329. var keepempty = container.data("keepempty") || false;
  330. var result = template || usearray ? [] : {};
  331. var keys = Object.keys(Object.values(data)[0] || {});
  332. var isassociative = !usearray && keys.indexOf("value") > -1 && (keys.length === 1 || (keys.length === 2 && keys.indexOf("key") > -1));
  333. if(isassociative && keys.length ===2){
  334. result = {};
  335. }
  336. $.each(data, function (i, j) {
  337. if (j) {
  338. if (isassociative) {
  339. if (keys.length === 2) {
  340. if (j.key != '' || keepempty) {
  341. result['__PLACEHOLDKEY__' + j.key] = j.value;
  342. }
  343. } else {
  344. //一维数组
  345. result.push(j.value);
  346. }
  347. } else {
  348. result.push(j);
  349. }
  350. }
  351. });
  352. textarea.val(JSON.stringify(result).replace(/__PLACEHOLDKEY__/g, ''));
  353. };
  354. //追加一行数据
  355. var append = function (container, row, initial) {
  356. var tagName = container.data("tag") || (container.is("table") ? "tr" : "dd");
  357. var index = container.data("index");
  358. var name = container.data("name");
  359. var template = container.data("template");
  360. var data = container.data();
  361. index = index ? parseInt(index) : 0;
  362. container.data("index", index + 1);
  363. row = row ? row : {};
  364. row = typeof row.key === 'undefined' || typeof row.value === 'undefined' ? {key: '', value: row} : row;
  365. var options = container.data("fieldlist-options") || {};
  366. var vars = {index: index, name: name, data: data, options: options, key: row.key, value: row.value, row: row.value};
  367. var html = template ? Template(template, vars) : Template.render(Form.config.fieldlisttpl, vars);
  368. var obj = $(html);
  369. if ((options.deleteBtn === false || options.removeBtn === false) && initial)
  370. obj.find(".btn-remove").remove();
  371. if (options.dragsortBtn === false && initial)
  372. obj.find(".btn-dragsort").remove();
  373. if ((options.readonlyKey === true || options.disableKey === true) && initial) {
  374. obj.find("input[name$='[key]']").prop("readonly", true);
  375. }
  376. obj.attr("fieldlist-item", true);
  377. obj.insertAfter($(tagName + "[fieldlist-item]", container).length > 0 ? $(tagName + "[fieldlist-item]:last", container) : $(tagName + ":first", container));
  378. if ($(".btn-append,.append", container).length > 0) {
  379. //兼容旧版本事件
  380. $(".btn-append,.append", container).trigger("fa.event.appendfieldlist", obj);
  381. } else {
  382. //新版本事件
  383. container.trigger("fa.event.appendfieldlist", obj);
  384. }
  385. return obj;
  386. };
  387. var fieldlist = $(".fieldlist", form);
  388. //表单重置
  389. form.on("reset", function () {
  390. setTimeout(function () {
  391. fieldlist.trigger("fa.event.refreshfieldlist");
  392. });
  393. });
  394. //监听文本框改变事件
  395. $(document).on('change keyup changed', ".fieldlist input,.fieldlist textarea,.fieldlist select", function () {
  396. var container = $(this).closest(".fieldlist");
  397. refresh(container);
  398. });
  399. //追加控制(点击按钮)
  400. fieldlist.on("click", ".btn-append,.append", function (e, row) {
  401. var container = $(this).closest(".fieldlist");
  402. append(container, row);
  403. refresh(container);
  404. });
  405. //移除控制(点击按钮)
  406. fieldlist.on("click", ".btn-remove", function () {
  407. var container = $(this).closest(".fieldlist");
  408. var tagName = container.data("tag") || (container.is("table") ? "tr" : "dd");
  409. $(this).closest(tagName).remove();
  410. refresh(container);
  411. });
  412. //追加控制(通过事件)
  413. fieldlist.on("fa.event.appendtofieldlist", function (e, row) {
  414. var container = $(this);
  415. append(container, row);
  416. refresh(container);
  417. });
  418. //根据textarea内容重新渲染
  419. fieldlist.on("fa.event.refreshfieldlist", function () {
  420. var container = $(this);
  421. var textarea = $("textarea[name='" + container.data("name") + "']", form);
  422. //先清空已有的数据
  423. $("[fieldlist-item]", container).remove();
  424. var json = {};
  425. try {
  426. var val = textarea.val().replace(/"(\d+)"\:/g, "\"__PLACEHOLDERKEY__$1\":");
  427. json = JSON.parse(val);
  428. } catch (e) {
  429. }
  430. $.each(json, function (i, j) {
  431. append(container, {key: i.toString().replace("__PLACEHOLDERKEY__", ""), value: j}, true);
  432. });
  433. });
  434. //拖拽排序
  435. fieldlist.each(function () {
  436. var container = $(this);
  437. var tagName = container.data("tag") || (container.is("table") ? "tr" : "dd");
  438. container.dragsort({
  439. itemSelector: tagName,
  440. dragSelector: ".btn-dragsort",
  441. dragEnd: function () {
  442. refresh(container);
  443. },
  444. placeHolderTemplate: $("<" + tagName + "/>")
  445. });
  446. if (typeof container.data("options") === 'object' && container.data("options").appendBtn === false) {
  447. $(".btn-append,.append", container).hide();
  448. }
  449. $("textarea[name='" + container.data("name") + "']", form).on("fa.event.refreshfieldlist", function () {
  450. //兼容旧版本事件
  451. $(this).closest(".fieldlist").trigger("fa.event.refreshfieldlist");
  452. });
  453. });
  454. fieldlist.trigger("fa.event.refreshfieldlist");
  455. });
  456. }
  457. },
  458. switcher: function (form) {
  459. form.on("click", "[data-toggle='switcher']", function () {
  460. if ($(this).hasClass("disabled")) {
  461. return false;
  462. }
  463. var switcher = $.proxy(function () {
  464. var input = $(this).prev("input");
  465. input = $(this).data("input-id") ? $("#" + $(this).data("input-id")) : input;
  466. if (input.length > 0) {
  467. var yes = $(this).data("yes");
  468. var no = $(this).data("no");
  469. if (input.val() == yes) {
  470. input.val(no);
  471. $("i", this).addClass("fa-flip-horizontal text-gray");
  472. } else {
  473. input.val(yes);
  474. $("i", this).removeClass("fa-flip-horizontal text-gray");
  475. }
  476. input.trigger('change');
  477. }
  478. }, this);
  479. if (typeof $(this).data("confirm") !== 'undefined') {
  480. Layer.confirm($(this).data("confirm"), function (index) {
  481. switcher();
  482. Layer.close(index);
  483. });
  484. } else {
  485. switcher();
  486. }
  487. return false;
  488. });
  489. },
  490. bindevent: function (form) {
  491. },
  492. slider: function (form) {
  493. if ($("[data-role='slider'],input.slider", form).length > 0) {
  494. require(['bootstrap-slider'], function () {
  495. $("[data-role='slider'],input.slider").removeClass('hidden').css('width', function (index, value) {
  496. return $(this).parents('.form-control').width();
  497. }).slider().on('slide', function (ev) {
  498. var data = $(this).data();
  499. if (typeof data.unit !== 'undefined') {
  500. $(this).parents('.form-control').siblings('.value').text(ev.value + data.unit);
  501. }
  502. });
  503. });
  504. }
  505. },
  506. tagsinput: function (form) {
  507. if ($("[data-role='tagsinput']", form).length > 0) {
  508. require(['tagsinput', 'autocomplete'], function () {
  509. $("[data-role='tagsinput']").tagsinput();
  510. form.on("reset", function () {
  511. setTimeout(function () {
  512. $("[data-role='tagsinput']").tagsinput('reset');
  513. }, 0);
  514. });
  515. });
  516. }
  517. },
  518. autocomplete: function (form) {
  519. if ($("[data-role='autocomplete']", form).length > 0) {
  520. require(['autocomplete'], function () {
  521. $("[data-role='autocomplete']").autocomplete({
  522. onSelect: function () {
  523. $(this).trigger('change').trigger('validate');
  524. }
  525. });
  526. });
  527. }
  528. },
  529. favisible: function (form) {
  530. if ($("[data-favisible]", form).length == 0) {
  531. return;
  532. }
  533. var checkCondition = function (condition) {
  534. var conditionArr = condition.split(/&&/);
  535. var success = 0;
  536. var baseregex = /^([a-z0-9\_]+)([>|<|=|\!]=?)(.*)$/i, strregex = /^('|")(.*)('|")$/, regregex = /^regex:(.*)$/;
  537. // @formatter:off
  538. var operator_result = {
  539. '>': function (a, b) {
  540. return a > b;
  541. },
  542. '>=': function (a, b) {
  543. return a >= b;
  544. },
  545. '<': function (a, b) {
  546. return a < b;
  547. },
  548. '<=': function (a, b) {
  549. return a <= b;
  550. },
  551. '==': function (a, b) {
  552. return a == b;
  553. },
  554. '!=': function (a, b) {
  555. return a != b;
  556. },
  557. 'in': function (a, b) {
  558. return b.split(/\,/).indexOf(a) > -1;
  559. },
  560. 'regex': function (a, b) {
  561. var regParts = b.match(/^\/(.*?)\/([gim]*)$/);
  562. var regexp = regParts ? new RegExp(regParts[1], regParts[2]) : new RegExp(b);
  563. return regexp.test(a);
  564. }
  565. };
  566. // @formatter:on
  567. var $disabledElements = form.find(':disabled').removeAttr('disabled');
  568. var dataArr = form.serializeArray(), dataObj = {}, fieldName, fieldValue;
  569. $disabledElements.attr('disabled', 'disabled');
  570. $(dataArr).each(function (i, field) {
  571. fieldName = field.name;
  572. fieldValue = field.value;
  573. fieldName = fieldName.substr(-2) === '[]' ? fieldName.substr(0, fieldName.length - 2) : fieldName;
  574. dataObj[fieldName] = typeof dataObj[fieldName] !== 'undefined' ? [dataObj[fieldName], fieldValue].join(',') : fieldValue;
  575. });
  576. $.each(conditionArr, function (i, item) {
  577. var basematches = baseregex.exec(item);
  578. if (basematches) {
  579. var name = basematches[1], operator = basematches[2], value = basematches[3].toString();
  580. if (operator === '=') {
  581. var strmatches = strregex.exec(value);
  582. operator = strmatches ? '==' : 'in';
  583. value = strmatches ? strmatches[2] : value;
  584. }
  585. var regmatches = regregex.exec(value);
  586. if (regmatches) {
  587. operator = 'regex';
  588. value = regmatches[1];
  589. }
  590. var chkname = "row[" + name + "]";
  591. if (typeof dataObj[chkname] === 'undefined') {
  592. return false;
  593. }
  594. var objvalue = dataObj[chkname];
  595. if ($.isArray(objvalue)) {
  596. objvalue = dataObj[chkname].join(",");
  597. }
  598. if (['>', '>=', '<', '<='].indexOf(operator) > -1) {
  599. objvalue = parseFloat(objvalue);
  600. value = parseFloat(value);
  601. }
  602. var result = operator_result[operator](objvalue, value);
  603. success += (result ? 1 : 0);
  604. }
  605. });
  606. return success === conditionArr.length;
  607. };
  608. form.on("keyup change click configchange", "input,textarea,select", function () {
  609. $("[data-favisible][data-favisible!='']", form).each(function () {
  610. var visible = $(this).data("favisible");
  611. var groupArr = visible ? visible.toString().split(/\|\|/) : [];
  612. var success = 0;
  613. $.each(groupArr, function (i, j) {
  614. if (checkCondition(j)) {
  615. success++;
  616. }
  617. });
  618. if (success > 0) {
  619. $(this).removeClass("hidden");
  620. } else {
  621. $(this).addClass("hidden");
  622. }
  623. });
  624. });
  625. //追加上忽略元素
  626. setTimeout(function () {
  627. var validator = form.data('validator');
  628. if (validator) {
  629. validator.options.ignore += ((validator.options.ignore ? ',' : '') + '.hidden[data-favisible] :hidden,.hidden[data-favisible]:hidden');
  630. }
  631. }, 0);
  632. $("input,textarea,select", form).trigger("configchange");
  633. }
  634. },
  635. api: {
  636. submit: function (form, success, error, submit) {
  637. if (form.length === 0) {
  638. Toastr.error("表单未初始化完成,无法提交");
  639. return false;
  640. }
  641. if (typeof submit === 'function') {
  642. if (false === submit.call(form, success, error)) {
  643. return false;
  644. }
  645. }
  646. var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
  647. type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
  648. url = form.attr("action");
  649. url = url ? url : location.href;
  650. //修复当存在多选项元素时提交的BUG
  651. var params = {};
  652. var multipleList = $("[name$='[]']", form);
  653. if (multipleList.length > 0) {
  654. var postFields = form.serializeArray().map(function (obj) {
  655. return $(obj).prop("name");
  656. });
  657. $.each(multipleList, function (i, j) {
  658. if (postFields.indexOf($(this).prop("name")) < 0) {
  659. params[$(this).prop("name")] = '';
  660. }
  661. });
  662. }
  663. //调用Ajax请求方法
  664. Fast.api.ajax({
  665. type: type,
  666. url: url,
  667. data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
  668. dataType: 'json',
  669. complete: function (xhr) {
  670. var token = xhr.getResponseHeader('__token__');
  671. if (token) {
  672. $("input[name='__token__']").val(token);
  673. }
  674. }
  675. }, function (data, ret) {
  676. $('.form-group', form).removeClass('has-feedback has-success has-error');
  677. if (data && typeof data === 'object') {
  678. //刷新客户端token
  679. if (typeof data.token !== 'undefined') {
  680. $("input[name='__token__']").val(data.token);
  681. }
  682. //调用客户端事件
  683. if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
  684. data.callback.call(form, data);
  685. }
  686. }
  687. if (typeof success === 'function') {
  688. if (false === success.call(form, data, ret)) {
  689. return false;
  690. }
  691. }
  692. }, function (data, ret) {
  693. if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
  694. $("input[name='__token__']").val(data.token);
  695. }
  696. if (typeof error === 'function') {
  697. if (false === error.call(form, data, ret)) {
  698. return false;
  699. }
  700. }
  701. });
  702. return true;
  703. },
  704. bindevent: function (form, success, error, submit) {
  705. form = typeof form === 'object' ? form : $(form);
  706. var events = Form.events;
  707. events.bindevent(form);
  708. events.validator(form, success, error, submit);
  709. events.selectpicker(form);
  710. events.daterangepicker(form);
  711. events.selectpage(form);
  712. events.cxselect(form);
  713. events.citypicker(form);
  714. events.datetimepicker(form);
  715. events.faupload(form);
  716. events.faselect(form);
  717. events.fieldlist(form);
  718. events.slider(form);
  719. events.switcher(form);
  720. events.tagsinput(form);
  721. events.autocomplete(form);
  722. events.favisible(form);
  723. },
  724. custom: {}
  725. },
  726. };
  727. return Form;
  728. });