简体   繁体   中英

What's the best regex for validating a field?

I use a regular expression to on a user-inputted field to make sure that they have entered between 1 and 20 characters.

Here's the code:

$post_validations = array("title" => '/^[[:alnum:][:punct:][:space:]]{1,100}$/');

But whenever a user enters a foreign character, or a special quote character from MS Word (I can't paste it into here, it converts it to a normal quote!) the regex doesn't return true, and it shows an error.

I wondered what would be the best regex to use?

Thanks

If all you want is know that it is between 1 and 20 characters, why not use strlen() ?

 $length = strlen($title);
 if($length >= 1 and $length <=20)
      echo "VALID";
 else
      echo "Invalid";

[EDIT]: Checking whether aplhanumeric or puctuation:

And if you also want to check whether the string contains any non-printable characters that may cause problem, just use ctype_graph()

 if(ctype_graph ($title))
      echo "Only alphanumeric or punctuation";
 else
      echo "Invalid non-printable characters found";

[EDIT 2]:

If you also want the spaces to be validated, just use this:

if(ctype_graph(str_replace(' ', '',$title))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM