-2

So i have got this almost completely working. The one thing i am stuck on is where to start in preg_match. I have read the manual here http://php.net/manual/en/function.preg-match.php but it doesn't exactly describe to me the syntax for creating my own validation. Example: for a text area, if i wanna only allow white space, letters, numbers and maybe some special characters(unlikely). Here is the code

<?php
    if(isset($_POST['name'])
            && isset($_POST['phone'])
            && isset($_POST['email'])) {

            if (empty($_POST["name"])) {
                    $nameErr = "Name is required";
            }
            else {
                    $name = $_POST["name"];
              // check if name only contains letters and whitespace for name
                    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                            $nameErr = "Only letters and white space 
                                allowed";
                    }
            }

            if (empty($_POST["phone"])) {
                    $phoneErr = "Phone number is required";
            }
            else {
                    $phone = $_POST["phone"];
                     // check if phone only contains numbers for phone
                    if (!preg_match('/^\(?[\d]{3}\)?\s?\-?[\d]{3}\s?\-?[\d]
                        {4}$/', $phone)) {
                            $phoneErr = "Only numbers allowed";
                    }
            }


            if (empty($_POST["email"])) {
                    $emailErr = "Email is required";
            }
            else {
                    $email = $_POST["email"];
                    // check if e-mail address is well-formed
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            $emailErr = "Invalid email format";
                    }
            }


            if($nameErr or $emailErr or $phoneErr){
                    echo $nameErr;
                    echo $phoneErr;
                    echo $emailErr;
                    die();
            }
            else if($data = $_POST['name'] . "\n" .
                    $_POST['email'] . "\n" .
                    $_POST['phone'] . "\n" .
                    $_POST['county'] . "\n" .
                    $_POST['floor'] . "\n" .
                    $_POST['descr'] . "\n"){

                    echo "Thank you for your inquery!" . "<br/>" .
                            "An estimator will be with you shortly.";

                    mail('theshadowcallsu@gmail.com', 'Estimation Request', 
                          $data);
            }
    }

 ?>
Bugs
  • 4,356
  • 9
  • 30
  • 39
  • 1
    *"and maybe some special characters"*: give the complete list of characters. – Casimir et Hippolyte Jul 07 '17 at 06:40
  • I figured the necessary ones for proper typing like "()" braces commas or hyphens – nicholascox2 Jul 07 '17 at 06:43
  • What does this code snippet have anything to do with your requirement? – revo Jul 07 '17 at 06:44
  • Just as a reference to show where my mind is at. Really i just need a good explaination on preg_match so i know how i'm going to actually configure it myself – nicholascox2 Jul 07 '17 at 06:48
  • `\d` already means `[0-9]`. Placing it in square brackets (`[\d]`) is useless. Why do you escape the dash (`\-`)? It is not a special character in `regex` (except when it is used in ranges but it is not the case here). – axiac Jul 07 '17 at 06:48
  • Possible duplicate of [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – revo Jul 07 '17 at 06:50
  • axiac: i pulled that off of an answered question here on SO and it worked when validating a phone number. – nicholascox2 Jul 07 '17 at 06:51
  • except it will fail on this phone number `(000)000-0000 ` {space} as there is no `trim()` often when copying stuff from emails there is extra white space... But anyway.. – ArtisticPhoenix Jul 07 '17 at 07:01
  • ArtisticPhoenix: that was the point of the post.... so i would get an explaination of how preg_match works when trying to create a customer validation.... – nicholascox2 Jul 07 '17 at 07:06
  • Like i tried to pull this answer from SO just now if (!preg_match('/^[a-z0-9 .\-]+$/i', $descr) and this one is not working. This is why i need to actually learn preg_match so i'm not just flipping through copy/paste and i can actually adjust it as needed. – nicholascox2 Jul 07 '17 at 07:20

1 Answers1

1

preg_match will apply a regex pattern to a string to see if the pattern matches the string

For input validation, you will try to match only the character you want in any order, and if the match failed (ie. there is a character not allowed) then the input contains character not declared in the pattern of string to match.

For example :

if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
   $nameErr = "Only letters and white space allowed";
}

It matches strings which contains only letter from a-z and A-Z and white spaces. If the string contains anything else, it won't match it.

For the text area, something like this should do the trick :

if (!preg_match("/^[a-zA-Z0-9 \(\)\n]*$/",$name)) {
   $nameErr = "not allowed";
}

What it does :

  • ^ : Start of the string
  • $ : End of the string
  • [a-zA-Z0-9 \(\)\n] : Match letters a-z, A-Z, numbers 0-9, (, ), new lines.
    • \n : Line return
    • \( and \) : Literraly the characters ( and ) because parenthesis are used to capture group in matching string

You can add between the [] the characters you want to allow.

See https://regex101.com/r/wmjrkw/1

Esteban
  • 1,554
  • 1
  • 6
  • 17
  • Thank you for the response. that makes sense for the part of a-z and A-Z. So what you did there for preg_match was just add ^ for the beginning of the string then add the validation in the square brackets and any special character needs to be escaped with a back slash? then end it with a $? Also, i tried this in the text area and it allows my text through no matter what even when i put all pound signs – nicholascox2 Jul 07 '17 at 11:47
  • @nicholascox2 I don't understand what you mean by "my textarea allow pound signs" did you have an example of you type and what you expect it will do? (with the regex you use) - Also I'll edit my answer with what `^` and '$' mean, but it is basic knwoledge about regex, you should search for documentation about "regular expression" (which is what `preg_match` use) – Esteban Jul 07 '17 at 12:41
  • What i meant is that i tried to submit the form with all the fields correctly filled out and for the text area (the one i'm testing) i filled it with stuff that is incorrect. Such as pound signs. Let me read up on regex. I was looking at preg_match information. Maybe that is where i was mistaken. I thought i was just googling wrong when i saw regex stuff pop up. – nicholascox2 Jul 08 '17 at 05:46