I've made a Validator that accepts rule objects to define validation rules.
$rules['name1'] = [new NotEmpty(), new MaxChars(20), new Alpha(true)];
$rules['name2'] = [new MaxChars(20), new Alpha(true)];
What my validator does with these rule objects, is that whenever it tries to validate an input, it will loop through every rule object and call the check()
method to see whether it's valid or not. And then return true or false with a list of the errors.
$validator = new Validator();
$validator->setRule('name1', $rules['name1']); //void
$validator->setRule('name2', $rules['name2']); //void
$validator->validate('name1', 'John Doe'); //true
$validator->validate('name2', ''); //should return true, but returns false
What would be a good way to indicate that an input can be optional?
I have a rule class NotEmpty
, but if I just leave it out of my rule declaration, my validator is still going to loop and check through every rule object that's been declared. While it should be ignoring the rules and just return true
. And that would be the ideal scenario.
I've thought about tightly coupling the NotEmpty
class with my Validator
class, e.g. checking if it's present in the rule array or not (which means required or optional). But I would rather have my classes decoupled, and I don't know if it's possible like that.
If anyone has a good suggestion, I can execute the further implementation myself.