simple-validator icon indicating copy to clipboard operation
simple-validator copied to clipboard

Optional validation for rulesets such as url and email

Open joemottershaw opened this issue 5 years ago • 0 comments

I know it's been a while since this package has been updated so apologies if you're no longer developing Simple Validator. But I was just wondering what the best approach is for optional data that needs validating only if data is present.

For example, I'm creating an edit profile form, within the form there is a field (website), that should validate as a url, but also pass if no data is entered.

As I see it, if the 'url' rule was declared, this also inadvertently calls a 'required' like method, since the filter_var in the url method will take the empty string and always return false, failing the validation. Should this not have an if null type statement wrapped around the filter_var, something similar to:

protected static function url($input) {
    if (empty($url) || is_null($url) || (trim($url) == '')) {
        return true;
    } else {
        return filter_var($url, FILTER_VALIDATE_URL);
    }
}

This would mean a rule with url could validate as optional and if it is required then you would use the rules 'required' and 'url', forcing an input along with url validation.

I understand this would cause backwards compatibility issues for users, unless an optional rule was added but I feel it would be a lot more complex to retrospectively handle this within other rule methods?

joemottershaw avatar Feb 07 '19 17:02 joemottershaw