Form validation used to occur at the server, after the client had entered all necessary data and then pressed the Submit button.
If some of the data that had been entered by the client had been in the wrong form or was simply missing, the server would have to send all the data back to the client and request that the form be submitted with correct information.
This was really a lengthy process and over burdening server.
JavaScript, provides a way to validate form’s data on the client’s computer before sending it to the web server. Form validation generally performs two functions.
Basic Validation – First of all, the form must be checked to make sure data was entered into each form field that required it. This would need just loop through each field in the form and check for data.
Data Format Validation – Secondly, the data that is entered must be checked for correct form and value. This would need to put more logic to test correctness of data.
Here in this tutorial I’ll show how to validate Username and Phone Fields on Form Submit Event?
Similar must read: JavaScript to Validate Email & Password Fields on From Submit Event
How to validate Username Field?
function validateUsername(fld) { var error = ""; var illegalChars = /\W/; // allow letters, numbers, and underscores if (fld.value == "") { fld.style.background = 'Yellow'; error = "You didn't enter a username.\n"; alert(error); return false; } else if ((fld.value.length < 5) || (fld.value.length > 15)) { fld.style.background = 'Yellow'; error = "The username is the wrong length.\n"; alert(error); return false; } else if (illegalChars.test(fld.value)) { fld.style.background = 'Yellow'; error = "The username contains illegal characters.\n"; alert(error); return false; } else { fld.style.background = 'White'; } return true; }
How to validate Phone Field?
function validatePhone(fld) { var error = ""; var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, ''); if (fld.value == "") { error = "You didn't enter a phone number.\n"; fld.style.background = 'Yellow'; alert(error); return false; } else if (isNaN(parseInt(stripped))) { error = "The phone number contains illegal characters. Don't include dash (-)\n"; fld.style.background = 'Yellow'; alert(error); return false; } else if (!(stripped.length == 10)) { error = "The phone number is the wrong length. Make sure you included an area code. Don't include dash (-)\n"; fld.style.background = 'Yellow'; alert(error); return false; } return true; }
NOTE: Please update your Form Field Name Value and Conditions accordingly.