Forum Moderators: coopster

Message Too Old, No Replies

String Pattern Validation

checks for certain string pattern

         

d40sithui

12:02 pm on Jul 24, 2007 (gmt 0)

10+ Year Member



Hi guys,
I want a function that checks for a certain string format when a user enters things in a text input. Ideally, the pattern should be restricted to ####-##-## . So four numbers folowed by a dash, followed by two numbers, another dash and two more numbers. this would be equivallent to the now() function i gues. Im really bad with this this, can anyone help.

PHP_Chimp

1:43 pm on Jul 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The format below should work for yyyy-mm-dd.
Check it as i have changed it around from dd-mm-yyyy.

$format = '%^(20)\d\d[-](0[1-9]¦1[012])[-](0[1-9]¦[12]\d¦3[01])$%';
$test = preg_match($format, $input);

PHP_Chimp

1:45 pm on Jul 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



humm pipes are not coming out properly, however you should be able to guess what characters the pipe should be.

d40sithui

1:57 pm on Jul 24, 2007 (gmt 0)

10+ Year Member



lol wel thats way shorter than what i was working on..which works btw hahah. thanks.

function valid_date($var){

if(empty($var)){
return false;
}

$year = substr($var, 0, 4); //year
$first_dash = substr($var,4,1); //first dash
$month = substr($var,5,2); //month
$second_dash = substr($var, 7,1); //2nd dash
$day = substr($var, 8, 2); //day

if(!is_numeric($year) ¦¦ strcasecmp($first_dash, "-")!=0 ¦¦ strcasecmp($second_dash, "-")!=0 ¦¦ empty($month) ¦¦ empty($day)){
return false;
}

$first_digit = substr($month, -2,1);
$second_digit = substr($month, -1,1);
//echo "\$first_digit: $first_digit<br>";
//echo "\$second_digit: $second_digit<br>";

//not numbers
if(!is_numeric($first_digit) ¦¦!is_numeric($second_digit)){
return false;
}

//months cannot go above 12
if($first_digit > 1){
return false;
}
if($first_digit == 1 && $second_digit > 2){
return false;
}

(int)$first_digit = substr($day, -2,1);
(int)$second_digit = substr($day, -1, 1);
if(!is_numeric($first_digit) ¦¦!is_numeric($second_digit)){
return false;
}

if($first_digit>3){
return false;
}

if($first_digit ==3 && $second_digit > 1){
return false;
}

return true;

}

PHP_Chimp

2:03 pm on Jul 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



regular expression both the best thing around and also the most annoying this you will ever come across ;)