I am trying to learn regular expression in PHP by creating simple patterns. Here I have a very simple example:
if($_POST){ $errors = array(); if(isset($_POST['name'])){ if(!preg_match('/^([a-zA-Z]{3,8})$/',$_POST['name'])){ $errors['name1'] = "Must enter Alphabet"; $errors['name2'] = ""Cant be less than 3"; } } if(count($errors)==0){ header("Location: pro.php"); exit(); } } ?> <form method="POST" target=""> First name: <input type="text" name="name"><br> <input type="submit" name="submit"> </form>
For me, validation works fine, but I had a problem presenting an error message based on an error. For example, I would like to display the error $errors['name1'] ONLY when no string was entered, and $errors['name2'] while entering numbers. I tried to select an expression according to two criteria:
if(isset($_POST['name'])) { if(!preg_match('/^([a-zA-Z])$/',$_POST['name'])) { $errors['name1'] = "Must enter Alphabet"; } if(preg_match('/^{3,8}$/',$_POST['name'])) { $errors['name2'] = "Cant be less than 3"; } }
but i get the following error 
Update
if(isset($_POST['name'])) { if(!preg_match('/^([a-zA-Z])$/',$_POST['name'])) { $errors['name1'] = "Must enter Alphabet"; } if ( ! preg_match( '/.{3,8}/', $_POST['name'] )) { $errors['name2'] = "Cant be less than 3"; } }
source share