flexrocks Posted March 4, 2017 Share Posted March 4, 2017 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 Quote Link to comment https://forums.phpfreaks.com/topic/303347-oop-form-validator-help/ Share on other sites More sharing options...
requinix Posted March 4, 2017 Share Posted March 4, 2017 the rule should look like this max_length:60|requiredAre 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:dThen check $type and use $data however is needed. Quote Link to comment https://forums.phpfreaks.com/topic/303347-oop-form-validator-help/#findComment-1543730 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.