This JavaScript code snippet adds inline validation to any form field (input, select and textarea).
Match an element against a given pattern and add a visual hint:
function cgPatternMatch(element, pattern) {
if ((element.value).match(pattern)) {
cgToggleError(element, 'valid');
} else {
cgToggleError(element, 'invalid');
}
}
Match an element against a given value:
function cgValueMatch(e) {
return (e.value !== '') ? true : false;
}
Check if email and email confirmation elements match and add a visual hint:
function cgEmailValidate(e1, e2) {
let pattern = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (
e1.value === e2.value &&
pattern.test(e1.value) &&
pattern.test(e2.value)
) {
cgToggleError(e2, 'valid');
} else {
cgToggleError(e2, 'invalid');
}
}
Match an element against a given pattern (based on validation type) and add a visual hint:
function cgFormValidate(element, type) {
if (type === 'alpha') {
let pattern = /^[a-zA-Z\-'.\s]+$/;
cgPatternMatch(element, pattern);
} else if (type === 'numeric') {
let pattern = /^[0-9]{1,10}$/;
cgPatternMatch(element, pattern);
} else if (type === 'alphanumeric') {
let pattern = /^[,'a-zA-Z0-9\-\s]+$/;
cgPatternMatch(element, pattern);
} else if (type === 'date') {
let pattern = /^[,'0-9\/\s]+$/;
cgPatternMatch(element, pattern);
} else if (type === 'email') {
let pattern = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
cgPatternMatch(element, pattern);
} else if (type === 'dropdown') {
if (element.value === '') {
cgToggleError(element, 'invalid');
} else {
cgToggleError(element, 'valid');
}
}
}
Next, custom data validation needs some additional HTML parameters and an onload()
event.
Read more about custom JavaScript form validation and implementation on my development blog.
Top comments (0)