Server Side form Validation in PHP
Server-side validation is another way to validate an HTML Form. In Server Side validation we can validate empty filed, input length, numeric value, valid email id and many more.
Create a HTML From. Create Name, Email , Password and contact no field. Below Structure of the form given below. I have embed PHP code in form to display error message.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<form method="post"> <table align="center" width="50%" border="0"> <?php if(isset($error)) { ?> <tr> <td id="error"><?php echo $error; ?></td> </tr> <?php } ?> <tr> <td><input type="text" name="uname" placeholder="User Name" value="<?php if(isset($uname)){echo $uname;} ?>" <?php if(isset($code) && $code == 1){ echo "autofocus"; } ?> /></td> </tr> <tr> <td><input type="text" name="email" placeholder="Your Email" value="<?php if(isset($email)){echo $email;} ?>" <?php if(isset($code) && $code == 2){ echo "autofocus"; } ?> /></td> </tr> <tr> <td><input type="text" name="mno" placeholder="Mobile No" value="<?php if(isset($mno)){echo $mno;} ?>" <?php if(isset($code) && $code == 3){ echo "autofocus"; } ?> /></td> </tr> <tr> <td><input type="password" name="pass" placeholder="Your Password" <?php if(isset($code) && $code == 4){ echo "autofocus"; } ?> /></td> </tr> <tr> <td><button type="submit" name="btn-signup">Sign Me Up</button></td> </tr> </table> |
PHP Script
This script validate empty input field, input length, validate email and validate numeric value. Put this code above the HTML tags
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?php if(isset($_POST['btn-signup'])) { $uname = trim($_POST['uname']); $email = trim($_POST['email']); $upass = trim($_POST['pass']); $mno = trim($_POST['mno']); if(empty($uname)) { $error = "enter your name !"; $code = 1; } else if(!ctype_alpha($uname)) { $error = "letters only !"; $code = 1; } else if(empty($email)) { $error = "enter your email !"; $code = 2; } else if(!preg_match("/^[_.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+.)+[a-zA-Z]{2,6}$/i", $email)) { $error = "not valid email !"; $code = 2; } else if(empty($mno)) { $error = "Enter Mobile NO !"; $code = 3; } else if(!is_numeric($mno)) { $error = "Numbers only !"; $code = 3; } else if(strlen($mno)!=10) { $error = "10 characters only !"; $code = 3; } else if(empty($upass)) { $error = "enter password !"; $code = 4; } else if(strlen($upass) < 8 ) { $error = "Minimum 8 characters !"; $code = 4; } else { ?> <script> alert('success'); document.location.href='index.php'; </script> <?php } } ?> |