PHP : Form & php check NULL & trim input example
Form Properties
-minlength=”3″
-required
-pattern=”^[a-zA-Z0-9]+$”
Form Example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<form name="addemp" method="post" action="save.php" class="form-horizontal"> <div class="form-group"> <div class="col-sm-2" align="right">Username:</div> <div class="col-sm-4" align="left"> <input name="usrename" type="text" minlength="3" class="form-control" placeholder="Username" required pattern="^[a-zA-Z0-9]+$" /> </div> </div> <div class="form-group"> <div class="col-sm-2" align="right">Password:</div> <div class="col-sm-4" align="left"> <input name="password" type="password" minlength="3" class="form-control" placeholder="Password" required pattern="^[a-zA-Z0-9]+$" /> </div> </div> <div class="form-group"> <div class="col-sm-2" align="right">ชื่อ:</div> <div class="col-sm-9" align="left"> <input name="membername" type="text" class="form-control" minlength="5" placeholder="ชื่อ" required /> </div> </div> </form> |
php check save.php
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 |
<meta charset="utf-8"> <?php //include require db $username = $_POST['username']; $password = $_POST['password']; $membername = $_POST['membername']; //chk null data from form if(!isset($username) || trim($username)==''){ echo "<script>"; echo "alert('กรอกข้อมูลไม่ครบถ้วน !');"; echo "window.history.back()"; echo "</script>"; }elseif(!isset($password) || trim($password)=='') { echo "<script>"; echo "alert('กรอกข้อมูลไม่ครบถ้วน !');"; echo "window.history.back()"; echo "</script>"; }elseif(!isset($membername) || trim($membername)=='') { echo "<script>"; echo "alert('กรอกข้อมูลไม่ครบถ้วน !');"; echo "window.history.back()"; echo "</script>"; }else{ //insert into or do something } mysql_close() ?> |
– trim = Check null input
*if input = null alert “กรอกข้อมูลไม่ครบถ้วน ! ” redirect to form.
1 |
E-mail: <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"> |
url or homepage
1 |
Homepage: <input type="url" name="website" pattern="https?://.+" title="Include http://"> |