Question

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

Was it helpful?

Solution

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

OTHER TIPS

user187291'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.
}
$char_re_good = "/^[0-9-]+$/";

Give that a try

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