Improve validate_form() JS helper function
This commit is contained in:
parent
f868343de5
commit
e48d1224f6
1 changed files with 8 additions and 2 deletions
|
@ -127,9 +127,10 @@ function show_form_modal(opts) {
|
||||||
/**
|
/**
|
||||||
* Validate and serialize form's data
|
* Validate and serialize form's data
|
||||||
* @param {jQuery} form The form element to validate and serialize
|
* @param {jQuery} form The form element to validate and serialize
|
||||||
|
* @param {bool} keep_empty Keep element with empty value in result (optional, default: false)
|
||||||
* @returns object|false The serialized form's data on success or false
|
* @returns object|false The serialized form's data on success or false
|
||||||
*/
|
*/
|
||||||
function validate_form(form) {
|
function validate_form(form, keep_empty = false) {
|
||||||
form.find(".is-invalid").removeClass("is-invalid");
|
form.find(".is-invalid").removeClass("is-invalid");
|
||||||
if (!form[0].checkValidity()) {
|
if (!form[0].checkValidity()) {
|
||||||
$(form[0].elements).each(function (idx, element) {
|
$(form[0].elements).each(function (idx, element) {
|
||||||
|
@ -140,7 +141,12 @@ function validate_form(form) {
|
||||||
var data = {};
|
var data = {};
|
||||||
jQuery.each(form.serializeArray(), function (idx, item) {
|
jQuery.each(form.serializeArray(), function (idx, item) {
|
||||||
item.value = item.value.trim();
|
item.value = item.value.trim();
|
||||||
if (item.value) data[item.name] = item.value;
|
if (item.value || keep_empty) data[item.name] = item.value;
|
||||||
|
});
|
||||||
|
form.find("input[type=checkbox]").each(function (idx, checkbox) {
|
||||||
|
if (!$(checkbox).val() && $(checkbox).attr("name")) {
|
||||||
|
data[$(checkbox).attr("name")] = $(checkbox).is(":checked");
|
||||||
|
}
|
||||||
});
|
});
|
||||||
console.log(data);
|
console.log(data);
|
||||||
return data;
|
return data;
|
||||||
|
|
Loading…
Reference in a new issue