views:

312

answers:

1

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

+1  A: 

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.

molf
Thanks! You saved me a few hours.
I was testing it out and noticed the line breaks were not working, then I checked your reply again, and now see....Thanks a lot, I suck at regexp.
@Whosane, I say this since you seem to be new here. If the answer by molf is good for you, it would be polite to accept it (click on the tick mark under the votes number on the left of the answer.
nik
thanks for the heads up nik.One more thing though, I think: d s m sdisplays as too short even with moving the mysql_real_escape... Right now it only says it is good if there are 3 characters on one line.
I think I go it.. /^(\S[.\s]*){3,}$/I think adding \s means you can have a new line. Maybe "." wasn't including new lines?
@Whosane, I updated the example. The s modifier should do the trick.
molf
thank you very much!