Validating form data using regex

2019-07-26 05:58发布

I'm newest and happy to be here in Stackoverflow. I am following this website since a long time.

I have an input/text field. (e.g. "Insert your name")

The script starts the following controls when the user sends data:

1) Control whether the field is empty or not.

2) Control whether the field goes over maximum characters allowed.

3) Control whether the field contain a wrong matched preg_match regex. (e.g. it contains numbers instead of only letters - without symbols and accents -).

The question is: why if i put this characters "w/", the script doesn't make the control? And it seems like the string bypass controls?


Hello to all guys and sorry if I'm late with the answer (and also for the non-code posted ^^).

Now, talking about my problem. I checked that the problem is on ONLY if I work offline (I use EasyPhp 5.3.6.1). Otherwise the regEx tested online is ok.

This is the code I use to obtain only what I said above:

    if (!preg_match('/^[a-zA-Z]+[ ]?[a-zA-Z]+$/', $name)) {

         echo "Error";

    }

As you can see, this code match:

  • A string that start (and finish) with only letters;
  • A string with only 0 or 1 empty space (for persons who has two name, i.e.: Anna Maria);

...right?!

(Please correct me if I am wrong)

Thanks to all!

Wart

3条回答
贼婆χ
2楼-- · 2019-07-26 06:48

It works fine.

<?php
$string = '\with';
if (preg_match('~[^0-9a-z]~i', $string)){
    echo "only a-Z0-9 is allowed"; //true
}

http://sandbox.phpcode.eu/g/18535/3

You have to make sure you don't put user input into your regex, because that would mean you'll probably check something wrong.

查看更多
迷人小祖宗
3楼-- · 2019-07-26 06:49

My reading of the requirements is

  • Only letters (upper or lower) can be provided.
  • Something must be provided (i.e. a non-zero length string).
  • There is a maximum length.

The code below checks this in a very simple manner and just echos any errors it finds; you probably want to do something more useful when you detect an error.

<?php

$max    = 10;
$string = 'w/';

// Check only letters; the regex searches for anything that isn't a plain letter
if (preg_match('/[^a-zA-Z]/', $string)){
    echo 'only letters are allowed';
} 

// Check a value is provided
$len = strlen($string);
if ($len == 0) {
    echo 'you must provide a value';
}

// Check the string is long to long
if ($len > $max) {
   echo 'the value cannot be longer than ' . $max;
}
查看更多
迷人小祖宗
4楼-- · 2019-07-26 07:03

You can also try this:

if (preg_match('/^[a-z0-9]{1,12}/im', $subject)) {
    \\ match
}

The above will only match similar to @genesis' post, but will only match if the $subject is between and including 1 - 12 characters long. The regex is also case insensitive.

查看更多
登录 后发表回答