Skip to content

Instantly share code, notes, and snippets.

@thanhan7914
Created November 12, 2020 07:47
Show Gist options
  • Select an option

  • Save thanhan7914/5f9b19b0dcc0d6114e2f91a819bd15ee to your computer and use it in GitHub Desktop.

Select an option

Save thanhan7914/5f9b19b0dcc0d6114e2f91a819bd15ee to your computer and use it in GitHub Desktop.
Jquery Fom Validation
/**
* Define rules
*
*/
const RULES = {
required: val => !!val && val.trim().length > 0,
min: (val, len) => val.length >= len,
max: (val, len) => val.length <= len,
};
/**
* Parse data
*
* @param any val
* @return object {func, args}
*/
function parseRuleFunc(val) {
let args = val.split(":");
let func = args.shift();
return { func, args };
}
/**
* Validate function
*
* @param jqueryElement $parent
* @param object option
* @return object { errors: object, passed: boolean}
*/
function validate($parent, option) {
let errors = {};
let status = true;
for (const [rule, validations] of Object.entries(option.rules)) {
let $tag = $parent.find(`[name="${rule}"]`);
let val = $tag.val();
let validate, passed;
let $error = $parent.find(`.p__text--error[data-for="${rule}"]`);
if ($error.length == 0) {
$error = $(
`<p class="p__text--error p__color--red" data-for="${rule}"></p>`
);
$error.insertAfter($tag);
}
$error.html("");
errors[rule] = [];
for (const [func, message] of Object.entries(validations)) {
validate = parseRuleFunc(func);
passed = RULES[validate.func](val, ...validate.args);
if (!passed) {
errors[rule].push(message);
$error.append(`<span class="span__display--block size-12">${message}</span>`);
status = false;
}
}
}
return {
errors,
passed: status
};
}
/**
* Apply validate to form
*
* @param string selector
* @param object option
* @return void
*/
function formValidate(selector, options) {
$(selector).keypress(function(e) {
if (e.keyCode == 13) return e.preventDefault();
});
$(selector).submit(function(ev) {
let result = validate($(this), options);
if (!result.passed) return ev.preventDefault();
});
}
@thanhan7914
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment