I am trying to learn Regular Expression in PHP by creating simple samples.Here I have very simple example as:
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>
To me, the validation is working fine but I have problem on presenting error message based on error.For example I would like to display error $errors['name1']
ONLY when not string has entered and $errors['name2']
while numbers entered. I tried to separate expression into two criteria as:
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 am getting 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";
}
}
Ok I am going to answer my question.Thanks to Masud Alam I figure it out how to do this in Regular Expression. The hint is using
if (!preg_match('/^[a-z]+$/i', $_POST['name'])) {
//
}
if (!preg_match('/^.{3,25}$/', $_POST['name'])) {
//
}
it works for me so far!
The error you are seeing is the result of not specifying match criteria in the regex before the {} operator. If you only care whether at least three of ANY character had been entered, try
if ( ! preg_match( '/.{3,8}/', $haystack ) )
You have to provide an 'atom' for the range to count. In this case, '.' signifies any single character.
How about:
if (isset($_POST['name'])) {
if (preg_match('/[^a-z])/i', $_POST['name'])) {
$errors['name1'] = "Must enter Alphabet";
}
if ( strlen($_POST['name']) < 3) {
$errors['name2'] = "Cant be less than 3";
}
if ( strlen($_POST['name']) > 8) {
$errors['name3'] = "Cant be more than 8";
}
}
If you really want to use regex:
if (preg_match('/[^a-z])/i', $_POST['name'])) {
$errors['name1'] = "Must enter Alphabet";
}
if ( ! preg_match('/^.{3,8}$/', $_POST['name']) ) {
$errors['name2'] = "Cant be less than 3";
}