开发者

What's the best regex for validating a field?

开发者 https://www.devze.com 2023-01-14 05:39 出处:网络
I use a regular expression to on a user-inputted field to make sure that they have entered between 1 and 20 characters.

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 sho开发者_C百科ws 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))
0

精彩评论

暂无评论...
验证码 换一张
取 消