JavaScript and PHP Validation
and Error Handling
With some foundation in both PHP and JavaScript, it’s time to bring these technologies together to create web forms that are as user-friendly as possible.
We’ll be using PHP to create the forms and JavaScript to perform client-side validation to ensure that the data is as complete and correct as it can be before it is submitted.
Final validation of the input will then be made by PHP, which will, if necessary,present the form again to the user for further modification.
In the process, we will cover validation and regular expressions in both JavaScript and PHP.
Validating User input with javascript
The best types of validation to do in JavaScript are checking that fields have content if they are not to be left empty, ensuring that email addresses conform to the proper format, and ensuring that values entered are within expected bounds.
The validate.html Document
Let’s begin with a general sign-up form, common on most sites that offer memberships or registered users. The inputs requested will be forename, surname, username,password, age, and email address. Example below provides a good template for such a form please copy and compile it to check results.
A form with JavaScript validation
<!DOCTYPE html>
<html>
<head>
<title>rbgtech form</title>
<style>
.signup {
border:1px solid #999999;
font: normal 14px helvetica;
color: #444444;
}
</style>
<script>
function validate(form)
{
fail = validateForename(form.forename.value)
fail += validateSurname(form.surname.value)
fail += validateUsername(form.username.value)
fail += validatePassword(form.password.value)
fail += validateAge(form.age.value)
fail += validateEmail(form.email.value)
if (fail == "") return true
else { alert(fail); return false }
}
function validateForename(field)
{
return (field == "") ? "No Forename was entered.\n" : ""
}
function validateSurname(field)
{
return (field == "") ? "No Surname was entered.\n" : ""
}
function validateUsername(field)
{
if (field == "") return "No Username was entered.\n"
else if (field.length < 5)
return "Usernames must be at least 5 characters.\n"
else if (/[^a-zA-Z0-9_-]/.test(field))
return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n"
return ""
}
function validatePassword(field)
{
if (field == "") return "No Password was entered.\n"
else if (field.length < 6)
return "Passwords must be at least 6 characters.\n"
else if (!/[a-z]/.test(field) || ! /[A-Z]/.test(field) ||
!/[0-9]/.test(field))
return "Passwords require one each of a-z, A-Z and 0-9.\n"
return ""
}
function validateAge(field)
{
if (isNaN(field)) return "No Age was entered.\n"
else if (field < 18 || field > 110)
return "Age must be between 18 and 110.\n"
return ""
}
function validateEmail(field)
{
if (field == "") return "No Email was entered.\n"
else if (!((field.indexOf(".") > 0) &&
(field.indexOf("@") > 0)) ||
/[^a-zA-Z0-9.@_-]/.test(field))
return "The Email address is invalid.\n"
return ""
}
</script>
</head>
<body>
<table border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee">
<th colspan="2" align="center">Signup Form</th>
<form method="post" action="adduser.php" onsubmit="return validate(this)">
<tr><td>Forename</td>
<td><input type="text" maxlength="32" name="forename"></td></tr>
<tr><td>Surname</td>
<td><input type="text" maxlength="32" name="surname"></td></tr>
<tr><td>Username</td>
<td><input type="text" maxlength="16" name="username"></td></tr>
<tr><td>Password</td>
<td><input type="text" maxlength="12" name="password"></td></tr>
<tr><td>Age</td>
<td><input type="text" maxlength="3" name="age"></td></tr>
<tr><td>Email</td>
<td><input type="text" maxlength="64" name="email"></td></tr>
<tr><td colspan="2" align="center"><input type="submit"
value="Signup"></td></tr>
</form>
</table>
</body>
</html>
Explanation of the code:
Between the <script> and </script> tags lies a single function called validate that itself calls up six other functions to validate each of the form’s input fields.
We’ll get to these functions shortly. For now I’ll just explain that they return either an empty string if a field validates, or an error message if it fails.
If there are any errors, the final line of the script pops up an alert box to display them.
Upon passing validation, the validate function returns a value of true; otherwise, it returns false. The return values from validate are important, because if it returns false, the form is prevented from being submitted.
This allows the user to close the alert pop up and make changes. If true is returned, no errors were encountered in the form’s fields and so the form is allowed to be submitted.
The second part of this example features the HTML for the form with each field and its name placed within its own row of a table.
This is pretty straightforward HTML,with the exception of the onSubmit="return validate(this)" statement within the opening <form> tag.
Using onSubmit, you can cause a function of your choice to be called when a form is submitted. That function can perform some checking and return a value of either true or false to signify whether the form should be allowed to be submitted.
The this parameter is the current object (i.e., this form) and is passed to the validate function just discussed. The validate function receives this parameter as the object form.
As you can see, the only JavaScript used within the form’s HTML is the call to return buried in the onSubmit attribute. Browsers with JavaScript disabled or not available will simply ignore the onSubbmit attribute, and the HTML will display just fine.
Validating the forename
validateForename is quite a short function that accepts the parameter field, which is the value of the forename passed to it by the validate function.
If this value is the empty string, an error message is returned; otherwise, an empty string is returned to signify that no error was encountered.
Validating the surname
The validateSurname function is almost identical to validateForename in that an error is returned only if the surname supplied was an empty string.
Validating the username
The validateUsername function has to allow through only the characters a-z, A-Z, 0-9, _ and -, and ensure that usernames are at least five characters long.
The if...else statements commence by returning an error if field has not been filled in. If it’s not the empty string, but is fewer than five characters in length,
another error message is returned.
Validating the password
Similar techniques are used in the validatePassword function. First the function checks whether field is empty, and if it is, returns an error.
Next, an error message is returned if a password is shorter than six characters.
One of the requirements we’re imposing on passwords is that they must have at least one each of a lowercase, uppercase, and numerical character, so the test function is called three times, once for each of these cases.
If any one of them returns false, one of the requirements was not met and so an error message is returned. Otherwise, the empty string is returned to signify that the password was OK.
Validating the age
validateAge returns an error message if field is not a number (determined by a call to the isNaN function), or if the age entered is lower than 18 or greater than 110.
Your applications may well have different or no age requirements. Again, upon successful validation,the empty string is returned.
Validating the email
In the last and most complicated example, the email address is validated with validateEmail. After checking whether anything was actually entered, and returning an error message if it wasn’t, the function calls the JavaScript indexOf function twice.
The first time a check is made to ensure there is a period (.) somewhere from at least the second character of the field, and the second checks that an @ symbol appears somewhere at or after the second character.
If those two checks are satisfied, the test function is called to see whether any disallowed characters appear in the field. If any of these tests fail, an error message is returned. The allowed characters in an email address are uppercase and lowercase letters, numbers, and the _, -, period, and @ characters, as detailed in the regular expression passed to the test method.
If no errors are found, the empty string is returned
to indicate successful validation. On the last line, the script and document are closed.
0 Comments