I've just finished creating this form validation but I want to make it public for beginner 'contact us forms'.
I was wondering if I can have some peoples' input on if they can understand/read my JavaScript. Although I know my JS works, it's better to be safe than to have 20 people asking what this does. It's just input feedback.
What I'm trying to achieve in my code is making fields required with JavaScript.
The following fields are REQUIRED:
- First Name
- Last Name
- Phone
Most of the functions such as alphaNumeric
only allows numbers and onlyAlphameric
only allows letters.
E.g for each function or what not, add a comment saying what it does.
For example, adding a comment:
This function does this and triggers that and so on.
JavaScript:
function elem(id) {
return document.getElementById(id);
};
window.onload = function () {
document.querySelector("#RadioGroup1_0").click();
var form = document.getElementById('form');
form.onsubmit = function (e) {
var rules = [
['first-name', elem('first-name').value.length > 0],
['last-name', elem('last-name').value.length > 0],
['email', elem('email').value.length > 0 && /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(elem('email').value)],
['phone', elem('phone').value.length > 7 && elem('phone').value.length < 11 && /^(\+\d{1,2})?[\d ()-]+$/.test(elem('phone').value)]
];
function myFunction()
{
document.getElementById("myForm").reset();
}
function alpha(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8);
}
var valid = true;
var firstFocus = null;
for (var i = 0; i < rules.length; i++) {
var parent = elem(rules[i][0]).parentNode;
if (!rules[i][1]) {
valid = false;
parent.children[2].style.display = "inline";
if (firstFocus == null) firstFocus = parent.children[1];
} else {
parent.children[2].style.display = "none";
}
}
if (!valid) {
firstFocus.focus();
return false;
}
return true;
};
};
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
} else if (e) {
var charCode = e.which;
} else {
return true;
}
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || (charCode === 8)) return true;
else return false;
} catch (err) {
alert(err.Description);
}
}
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
//document.getElementById("phone").style.display = ret ? "none" : "inline";
return ret;
}