Urdaneta City University Elective 102: Server Side Coding
College of Computer Studies Module 5: Form Validations
PHP Form Validations
OBJECTIVES At the end of the module, students are expected to:
1. Differentiate the client side validation to server side validations
2. Identify the validation fields
3. Validate all required fields
Client Side Validation vs. Server Side Validation
Client-Side Validation − Validation is performed on the client machine web
browsers.
Server Side Validation − after submitted by data, the data has sent to a server
and perform validation checks in server machine.
Validation Fields
Name Should require letters and white-spaces
Email Email
Website Should require a valid URL
Radio Must be selectable at least once
Check Box Must be checkable at least once
Drop Down menu Must be selectable at least once
preg_match function
It searches string for pattern, returning true if pattern exists, and false otherwise.
Validate Name
Syntax and Pattern
$name = $_POST[‘name’];
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
It shows a simple way to check if the name field only contains letters and whitespace. If
the value of the name field is not valid, then store an error message.
Validate Email
Syntax and Pattern
$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
dnnelcaguin 1
Urdaneta City University Elective 102: Server Side Coding
College of Computer Studies Module 5: Form Validations
$emailErr = "Invalid email format";
}
If the e-mail address is not well-formed, then store an error message:
Validate URL
Syntax and Pattern
$website = POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i", $website)) {
$websiteErr = "Invalid URL";
}
It shows a way to check if a URL address syntax is valid (this regular expression also
allows dashes in the URL). If the URL address syntax is not valid, then store an error message:
Validate Number
Syntax and Pattern
$age = $_POST[‘age’];
if (!preg_match("/^[0-9]*$/",$age)) {
$ageErr = "Only numbers allowed";
}
It shows a simple way to check if the age field only contains numbers. If the value of the
name field is not valid, then store an error message.
Validate Decimal
Syntax and Pattern
$price = $_POST["price"];
if (!filter_var($pricel, FILTER_VALIDATE_FLOAT)) {
$price = “Invalid decimal format";
}
It shows a simple way to check if the price field only contains numbers with decimal. If
the value of the name field is not valid, then store an error message.
dnnelcaguin 2