Last active
February 20, 2017 10:06
-
-
Save rintoug/33642776783996c5cfab3a5a1190fdb5 to your computer and use it in GitHub Desktop.
Server Side Form Validation using Regular Expressions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Declaring the variables | |
$error_name = ''; | |
$error_email= ''; | |
$error_gender =''; | |
//Validation part | |
if ($_SERVER['REQUEST_METHOD'] == 'POST') { | |
$name = $_POST['name']; | |
$email = $_POST['email']; | |
$gender = $_POST['gender']; | |
//only characters and space is allowed | |
if(!preg_match('/^[a-z ]+$/i', $name)) { | |
$error_name = "Alowed charaters are a-z "; | |
} | |
$regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/'; | |
if(!preg_match($regex, $email)) { | |
$error_email = "Invalid email"; | |
} | |
if(empty($gender)) { | |
$error_gender = "Select gender"; | |
} | |
if(empty($error_name) && (empty($error_email) && empty($error_gender))) { | |
//your insert to database | |
} | |
} | |
?> | |
<form method="post"> | |
<?php print $error_name?> | |
<br> | |
<label>Name</label> | |
<input type="text" name="name" value=""> | |
<br><br> | |
<?php print $error_email?> | |
<br> | |
<label>Email</label> | |
<input type="email" name="email" value=""> | |
<br><br> | |
<?php print $error_gender?> | |
<br> | |
<label>Gender</label> | |
<select name="gender"> | |
<option value="male">Male</option> | |
<option value="female">Female</option> | |
</select> | |
<br><br> | |
<input type="submit" name="submit" value="Submit"> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment