PHP Validation using JavaScript

15/04/2017   03:58:56 PM

Hello, in this tutorial I will explain how to validate fields on the php form using javascript. JavaScript form validation is to provide a method to check the user entered information before they can even submit it. JavaScript also lets you display helpful alerts to inform the user what information they have entered incorrectly and how they can fix it.

1) Create FormValidation.js file

window.onload = init;
// The "onload" handler. Run after the page is fully loaded.
function init() {
// Attach "onsubmit" handler
document.getElementById("theForm").onsubmit = validateForm;
// Attach "onclick" handler to "reset" button
document.getElementById("reset").onclick = clearDisplay;
// Set initial focus
document.getElementById("name").focus();
}
function validateForm() {
return (isNotEmpty("name", "Please enter your name!")
&& isNumeric("zipcode", "Please enter a 5-digit zip code!")
&& isLengthMinMax("zipcode", "Please enter a 5-digit zip code!", 5, 5)
&& isSelected("country", "Please make a selection!")
&& isChecked("gender", "Please check a gender!")
&& isChecked("color", "Please check a color!")
&& isNumeric("phone", "Please enter a valid phone number!")
&& isValidEmail("email", "Enter a valid email!")
&& isLengthMinMax("password", "Enter a valid password!", 6, 8)
&& verifyPassword("password", "pwVerified", "Different from the password!"));
}
 
// Retrun true if the input value is not empty
function isNotEmpty(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length != 0); // boolean
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
function showMessage(isValid, inputElement, errorMsg, errorElement) {
if (!isValid) {
// Put up error message on errorElement or via alert()
if (errorElement != null) {
errorElement.innerHTML = errorMsg;
} else {
alert(errorMsg);
}
// Change "class" of inputElement, so that CSS displays differently
if (inputElement != null) {
inputElement.className = "error";
inputElement.focus();
}
} else {
// Reset to normal display
if (errorElement != null) {
errorElement.innerHTML = "";
}
if (inputElement != null) {
inputElement.className = "";
}
}
}
 
// Return true if the input value contains only digits (at least one)
function isNumeric(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.search(/^[0-9]+$/) != -1);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}

// Return true if the input value contains only letters (at least one)
function isAlphabetic(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = inputValue.match(/^[a-zA-Z]+$/);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if the input value contains only digits and letters (at least one)
function isAlphanumeric(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = inputValue.match(/^[0-9a-zA-Z]+$/);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if the input length is between minLength and maxLength
function isLengthMinMax(inputId, errorMsg, minLength, maxLength) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value.trim();
var isValid = (inputValue.length >= minLength) && (inputValue.length <= maxLength);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
// Return true if the input value is a valid email address
// (For illustration only. Should use regexe in production.)
function isValidEmail(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value;
var atPos = inputValue.indexOf("@");
var dotPos = inputValue.lastIndexOf(".");
var isValid = (atPos > 0) && (dotPos > atPos + 1) && (inputValue.length > dotPos + 2);
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
 
// Return true if selection is made (not default of "") in <select> input
function isSelected(inputId, errorMsg) {
var inputElement = document.getElementById(inputId);
var errorElement = document.getElementById(inputId + "Error");
var inputValue = inputElement.value;
// You need to set the default value of <select>'s <option> to "".
var isValid = inputValue != "";
showMessage(isValid, inputElement, errorMsg, errorElement);
return isValid;
}
 
// Return true if the one of the checkboxes or radio buttons is checked
function isChecked(inputName, errorMsg) {
var inputElements = document.getElementsByName(inputName);
var errorElement = document.getElementById(inputName + "Error");
var isChecked = false;
for (var i = 0; i < inputElements.length; i++) {
if (inputElements[i].checked) {
isChecked = true; // found one element checked
break;
}
}
showMessage(isChecked, null, errorMsg, errorElement);
return isChecked;
}
// Verify password. The password is kept in element with id "pwId".
// The verified password in id "verifiedPwId".
function verifyPassword(pwId, verifiedPwId, errorMsg) {
var pwElement = document.getElementById(pwId);
var verifiedPwElement = document.getElementById(verifiedPwId);
var errorElement = document.getElementById(verifiedPwId + "Error");
var isTheSame = (pwElement.value == verifiedPwElement.value);
showMessage(isTheSame, verifiedPwElement, errorMsg, errorElement);
return isTheSame;
}

// The "onclick" handler for the "reset" button to clear the display
function clearDisplay() {
var elms = document.getElementsByTagName("*"); // all tags
for (var i = 0; i < elms.length; i++) {
if ((elms[i].id).match(/Error$/)) { // no endsWith() in JS?
elms[i].innerHTML = "";
}
if (elms[i].className == "error") { // assume only one class
elms[i].className = "";
}
}
// Set initial focus
document.getElementById("name").focus();
}

 

2) Create FormValidation.css file

.red { /* for error messages */

color: red;

}

input.error { /* for the error input text fields */

border: 1px red inset;

padding: 2px;

}

table {

border: 0;

}

td {

margin: 0;

padding: 3px 10px 3px 3px;

}

 

3) Create index.php page

<link rel="stylesheet" href="FormValidation.css">

<script type="text/javascript" src="FormValidation.js" ></script>

<form id="theForm" method="get">

<table>

<tr>

<td>Name<span class="red">*</span></td>

<td><input type="text" id="name" name="name"/></td>

<td id="nameError" class="red">&nbsp;</td></tr>

 

<td>Zip Code<span class="red">*</span></td>

<td><input type="text" id="zipcode" name="zipcode" /></td>

<td id="zipcodeError" class="red">&nbsp;</td></tr>

<tr>

<td>Country<span class="red">*</span></td>

<td><select id="country" name="country">

<option value="" selected>Please select...</option>

<option value="AA">AA</option>

<option value="BB">BB</option>

<option value="CC">CC</option>

</select><br /></td>

<td id="countryError" class="red">&nbsp;</td></tr>

<tr>

<td>Gender<span class="red">*</span></td>

<td><input type="radio" name="gender" value="m" />Male

<input type="radio" name="gender" value="f" />Female</td>

<td id="genderError" class="red">&nbsp;</td></tr>

<tr>

<td>Preferences<span class="red">*</span></td>

<td><input type="checkbox" name="color" value="r" />Red

<input type="checkbox" name="color" value="g" />Green

<input type="checkbox" name="color" value="b" />Blue</td>

<td id="colorError" class="red">&nbsp;</td></tr>

<tr>

<td>Phone<span class="red">*</span></td>

<td><input type="text" id="phone" name="phone" /></td>

<td id="phoneError" class="red">&nbsp;</td></tr>

<tr>

<td>Email<span class="red">*</span></td>

<td><input type="text" id="email" name="email" /></td>

<td id="emailError" class="red">&nbsp;</td></tr>

<tr>

<td>password (6-8 characters)<span class="red">*</span></td>

<td><input type="password" id="password" name="password" /></td>

<td id="passwordError" class="red">&nbsp;</td></tr>

<tr>

<td>Verify password<span class="red">*</span></td>

<td><input type="password" id="pwVerified" name="pwVerified" /></td>

<td id="pwVerifiedError" class="red">&nbsp;</td></tr>

<tr>

<td>&nbsp;</td>

<td><input type="submit" value="SEND" id="submit"/>&nbsp;

<input type="reset" value="CLEAR" id="reset"/></td>

<td>&nbsp;</td></tr>

</table>

</form>


Output

                   

Support us by Sharing