Problem using regex in simple PHP validation

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 enter image description here

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"; } } 
+4
source share
3 answers

Ok, I'm going to answer my question. Thanks for Masood Alam. I will figure out how to do this in Regular Expression. The tooltip is used

  if (!preg_match('/^[az]+$/i', $_POST['name'])) { // } if (!preg_match('/^.{3,25}$/', $_POST['name'])) { // } 

it works for me so far!

0
source

The error you see is the result of not specifying matching criteria in the regular expression before the {} operator. If you don't care if at least three ANY characters are entered, try

 if ( ! preg_match( '/.{3,8}/', $haystack ) ) 

You must specify an atom for the range to be counted. In this case, '.' means any character.

0
source

What about:

 if (isset($_POST['name'])) { if (preg_match('/[^az])/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('/[^az])/i', $_POST['name'])) { $errors['name1'] = "Must enter Alphabet"; } if ( ! preg_match('/^.{3,8}$/', $_POST['name']) ) { $errors['name2'] = "Cant be less than 3"; } 
0
source

Source: https://habr.com/ru/post/1499729/


All Articles