Validate a correct month format 1-12???

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bordman
Forum Newbie
Posts: 16
Joined: Thu Jan 26, 2006 8:20 am
Location: RI

Validate a correct month format 1-12???

Post by bordman »

feyd | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]


Hi, I'm trying to make sure a user can only put in 1 - 12 for a month field. 

Here's the code I'm trying:

Code: Select all

//policy_eff_date_mo Policy Start Date Month
	$policy_eff_date_mo = settype($policy_eff_date_mo, int) + 1;
	if($policy_eff_date_mo == '' || ($policy_eff_date_mo >= 1 AND $policy_eff_date_mo <= 12))  {
		$error_msg.="Please enter a Policy Start Date month. (i.e. Feb = 2 or Dec = 12)<br>";
	}

When I enter 22 the validation doesn't work(which it shouldn't) but when I enter 8 or 08 I get back 2 and still get the error message. What am I doing wrong??

Thanks!!
ROB


feyd | Please use

Code: Select all

and

Code: Select all

tags where appropriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

settype() doesn't return the new value. It returns true on success, false on failure. The new value is the variable you passed in itself. That explains the results you are getting.

Now, you have a logic error. You are checking if the value is between 1 and 12, inclusively. If it is, you give the error. You need to invert the expression:

Code: Select all

if($policy_eff_date_mo < 1 or $policy_eff_date_mo > 12)  {
        $error_msg.="Please enter a Policy Start Date month. (i.e. Feb = 2 or Dec = 12)<br>";
    }
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

Code: Select all

$valid = FALSE;
if (!empty($input)){
	if (gettype($input) == "string"){
		if (ctype_digit($input)){
			settype($input, "integer");
		}
	}
	
	if (gettype($input) == "integer"){
		if ($input >= 1 && $input <= 12) $valid = TRUE;		
	}else{
		return FALSE;
	}
}
Post Reply