• We just launched and are currently in beta. Join us as we build and grow the community.

How to Validate HTML Form Using PHP/jQuery?

raigen

Network Pentester
R Rep
0
0
0
Rep
0
R Vouches
0
0
0
Vouches
0
Posts
44
Likes
75
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
Hi there,

Today I am going to show how to validate form using jquery and php.

HTML Forms are one of the main points of interaction between a user and a web site or application

php $name = '';
$gender = '';
$address = '';
$email = '';
$username = '';
$password = '';
$output = '';

if($_POST) {
// collect all input and trim to remove leading and trailing whitespaces
$name = trim($_POST['name']);
$gender = trim($_POST['gender']);
$address = trim($_POST['address']);
$email = trim($_POST['email']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);

$errors = array();

// Validate the input
if (strlen($name) == 0)
array_push($errors, "Please enter your name");

if (!(strcmp($gender, "Male") || strcmp($gender, "Female") || strcmp($gender, "Other")))
array_push($errors, "Please specify your gender");

if (strlen($address) == 0)
array_push($errors, "Please specify your address");

if (!filter_var($email, FILTER_VALIDATE_EMAIL))
array_push($errors, "Please specify a valid email address");

if (strlen($username) == 0)
array_push($errors, "Please enter a valid username");

if (strlen($password) < 5)
array_push($errors, "Please enter a password. Passwords must contain at least 5 characters.");

// If no errors were found, proceed with storing the user input
if (count($errors) == 0) {
array_push($errors, "No errors were found. Thanks!");
}

//Prepare errors for output
$output = '';
foreach($errors as $val) {
$output .= "<p class='output'$val";
}

}

?>

Define some CSS
Load jQuery and the validate plugin
jQuery Form Validation code

php echo $output; ?
The form that will be parsed by jQuery before submit

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.

2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.


Download
You must upgrade your account or reply in the thread to view hidden text.
 

450,053

322,753

322,762

Top