开发者

Adding validation to a class in PHP

开发者 https://www.devze.com 2023-01-22 12:34 出处:网络
I have several classes (for a Form generator class thing I\'m making...I know sad.. :( ),anyway, the hierarchy is as follows:

I have several classes (for a Form generator class thing I'm making...I know sad.. :( ),anyway, the hierarchy is as follows:

class HTML_Form accepts abstract class FormElement objects (using type hinting). FormElement class has several children classes such as Textbox, Password, Radio .etc

How would I add validation to these, for example the method I'm trying to make in class HTML_Form is:

$form = new HTML_Form($name);

$form->addElement($type, $name, $validation);

I hope everybody underst开发者_JAVA技巧and... and yes I'm such a noob.


If you're trying to do server side validation, once a POST/GET is received load the form object with the submitted values.

To your form element classes add a function is_valid(). You can add whatever validations you want there. If you want to use a separate validation function(one that is not element specific but form specific), meaning somebdoy submitted a form that took an reference ID to a database object, and you want to make sure that is the correct object, so your input_text form element would not naturally cover this validation. Add another function to your form_element objects called "set_validation_function". from there pass in an array of array(class, function). Then update your is_valid() function to check to see if a validation_function is set and if it is use, call_user_function(array(class, function), params) to call the defined function.


I would probably make a generic Validator class and call it when you add an element. Strict OOP those elements should be different, i.e.

$input = new InputFormElement(array('name' => 'firstname', 'id' => 'firstname'), $validation);
$form->addElement($input);

/* ... */
if($input->validate())
0

精彩评论

暂无评论...
验证码 换一张
取 消