Jump to content

OOP Form validator help


flexrocks

Recommended Posts

So i have a pretty basic form validator that checks if the field is valid but i'm having hard time trying to implement rules. i have already implemented a few rules but how can i implement max_length and min_length?

here is my validate function

public function validate($field,$value,$rules)
   {
   	 $field = ucfirst($field);
   	 $rules = explode('|',$rules);
   	 foreach($rules as $rule)
   	 {
   	 	switch($rule)
   	 	{
   	 		case 'required':
   	 			$this->shouldBeRequired($field, $value);
   	 			break;
   	 		case 'string':
   	 			$this->shouldBeString($field,$value);
   	 		    break;
   	 		case 'email':
   	 			$this->shouldBeEmail($field, $value);
   	 			break;
   	 		case 'number':
   	 			$this->shouldBeNumber($field,$value);
//    	 		default:
//    	 			throw new ErrorException("$rule doesn't exist");
   	 	}
   	 }
   }

i want to do case 'max_length' but i have no idea how. the rule should look like this max_length:60|required any help is appreciated

Link to comment
Share on other sites

the rule should look like this max_length:60|required

Are you married to that idea? Because something like

array("max_length" => 60, "required" => true)
looks a lot nicer to me.

 

To answer the question as asked, you need to break apart $rule on the colon so you can have the first part (the type of rule) separate from the rest (data for the rule). explode() can do it

list($type, $data) = explode(":", $rule, 2); // a:b:c:d -> a, b:c:d
Then check $type and use $data however is needed.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.