I'm currently working on an OO PHP application. I have a class called validation which I would like to use to check all of the data submitted is valid, however I obviously need somewhere to define the rules for each property to be checked. At the moment, I'm using arrays during the construction of a new object. eg:
$this->name = array(
'maxlength' => 10,
'minlength' => 2,
'required' => true,
'value' => $namefromparameter
)
One array for each property.
I would then call a static method from the validation class which would carry out various checks depending on the values defined in each array.
Is there a more efficient way of doing this? Any advice appreciated. Thanks.
An important part of the OOP is too always keep your object in a valid state. Therefore, validation should be done after an input that could modify the object. It's always good to validate data comming from properties/set, parameters to functions and constructor.
Validation in PHP is the process where we check if the input information in the various fields in any form such as text, checkbox or radio button, etc, submitted by the end-user in the form is correct or not using HTML code.
Introduction to PHP form validation There are two types of validations: client-side & server-side: The client-side validation is performed in the web browsers of the users. To validate data at the client side, you can use HTML5 validation or JavaScript.
php", to replace the :attribute name (input name) for a proper to read name (example: first_name > First name) . It seems very simple to use, but the validator doesn't show the "nice names". And the validation in the controller: $validation = Validator::make($input, $rules, $messages);
I know the associative array is used commonly to configure things in PHP (it's called magic container pattern and is considered bad practice, btw), but why don't you create multiple validator classes instead, each of which able to handle one rule? Something like this:
interface IValidator {
public function validate($value);
}
$validators[] = new StringLengthValidator(2, 10);
$validators[] = new NotNollValidator();
$validators[] = new UsernameDoesNotExistValidator();
This has multiple advantages over the implementation using arrays:
array('reqiured' => true)
)EDIT: Here is a link to an answer I gave to a different question, but that is mostly applicable to this one as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With