tags:

views:

50

answers:

3
+1  Q: 

Preg match problem

Hello!

I try to "validate" a date field. I only want to allow, numeric chars and - character.

 $born_date=$_POST['date'];
 $goodchars = array("1","2","3","4","5","6","7","8","9","0","-");
 $char_re_good = '/['.preg_quote(join('', $goodchars), '/').']/';
       if (!(preg_match($char_re_good, $born_date))) {
            echo "not ok, contain INVALID chars"
       }else{
            echo "ok, contain valid chars"
       }

If i try to search for "1960" then OK. If i try to search for " asdfg" then NOT OK. But if i search for "1960/" then the output is OK. I dont understand why.

Could you help me modify to check if user only "0-9" and "-" chars fill out the field.

Thank you

A: 
$char_re_good = "/^[0-9-]+$/";

Give that a try

inkedmn
+6  A: 

you need to "anchor" your expression, i.e. insert start of string ^ and end of string $ markers.

 preg_match('/^[0-9-]+$/', $born_date);

however, preg_match is not a way to validate dates. For example, the above will accept "99999999" etc

stereofrog
+1 for the word "anchor", which I couldn't remember
Yacoby
I'm not completely sure, but don´t you have to put the **-** at the start in a character class or escape it?
jeroen
Stereofrog - works well. Thank you. Its not a real validate. I dont need it. I just wanna sure if valid characters filled..
Holian
@jeroen: dash is taken as is on the either edge of the class, ie [ab-] [-ab] and [a\-b] are the same
stereofrog
Aaaaaaaah, thanks for the info, didn´t know that...
jeroen
+5  A: 

stereofrog's regex will match date characters only, which is what you want. A quick way to validate a date is to try and convert it to a timestamp via strtotime():

if (strtotime($date_str)!==false) {
  // The date is valid.
}
pygorex1
this is a simple search form. users can hit only 1960 without day and month. im not sure, but if i convert 1960 with strtotime, then i get false result.?! I will try.
Holian