Skip to content

Instantly share code, notes, and snippets.

@yuval-a
Created July 26, 2015 23:02
Show Gist options
  • Save yuval-a/985c941299c2f148555d to your computer and use it in GitHub Desktop.
Save yuval-a/985c941299c2f148555d to your computer and use it in GitHub Desktop.
Form validation - one function
// put 'req' on the elements of any required input fields. Don't use the 'required' attribute, otherwise the default action
// will trigger.
function onFormSubmit(form) {
var isValid = true;
Array.prototype.forEach.call(form.elements, function (e) {
if ((e.value.length == 0 || ! /\S/g.test(e.value)) && e.getAttribute('req') !== null && e.getAttribute('req') !== undefined) {
isValid = false;
e.value = "";
if (e.getAttribute('req') == "") {
var ph = e.getAttribute('placeholder');
e.setAttribute('placeholder', ph + " (חובה)");
e.setAttribute('req', 'marked');
}
}
});
if (!isValid) return false;
var email = form.elements['youremail'].value;
if (email.indexOf('@')<0 || email.indexOf('.')<0) {
alert("אנא הכנס כתובת דואל תקנית");
form.elements['youremail'].focus();
return false;
}
if (/[^\d\+\-]/g.test(form.elements['yourphone'].value)) {
alert("אנא הכנס מספר טלפון תקני");
form.elements['yourphone'].focus();
return false;
}
// Do Submit here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment