Question

I have a textarea. I am trying to check that it contains atleast 3 non-whitespace characters in javascript, and if it does, I need to recheck the posted message in php.

I think once I get it working in php, I can use the same regexp for javascript. However, the whitespaces are messing it up.

I don't understand why the following does not work in php:

$msg = mysql_real_escape_string($_POST["msg"]);

if(!preg_match('/[\S]{3,}/',$msg)){
     echo 'too short';
}

To me it seems like that requires atleast 3 "non-whitespace character". However if I enter:

f f f

It says it is too short. And

f 

d

passes. I've tried adding the "g" flag, and playing with ^ and $ surrounding the regexp.

Thanks for any tips

Was it helpful?

Solution

Your regex matches 3 subsequent non-whitespace characters.

The following matches 3 non-whitespace characters, separated by anything:

/(\S.*){3,}/

To perform validation across multiple lines, add the s modifier:

/(\S.*){3,}/s

You should also do the validation before calling mysql_real_escape_string. In your example, the second string is converted to f\r\nd or f\nd first. It now contains 3 subsequent non-whitespace characters! As you can see, this screws up validation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top