jhthorsen / json-validator

:cop: Validate data against a JSON schema
https://metacpan.org/release/JSON-Validator
56 stars 58 forks source link

Created method JSON::Validator->set_format_validator #148

Closed rolosworld closed 5 years ago

rolosworld commented 5 years ago

The method JSON::Validator->set_format_validator lets you set custom format validators or replace a default one.

Summary

To achieve my objective I moved $_default_formats hash outside the method JSON::Validator->_build_formats to prevent new hash from being created everytime the method gets called.

Then modified JSON::Validator->_build_formats to make a copy of the hash on the object that called the method. The reason I made this change is so each object created can have their own format validators.

FInally, I created the method JSON::Validator->set_format_validator which simply sets the validator subroutine for the given format on the current object.

Motivation

While using the module in a personal project I had some issues with how the email and uri formats were validated. I managed to create a workaround by overriding the JSON::Validator->_build_format method with modules that specialize validating those formats (Email::Valid and Data::Validate::URI) . I figured it could be useful to change the format validators, so here we are.

References

https://github.com/mojolicious/json-validator/issues/68

test.pl.txt

jhthorsen commented 5 years ago

Even though there’s no custom method for adding/changing formats, but you can already just manipulate the “formats” attribute, which holds all of them in a hash or create new objects with the attribute set in the constructor.

A shared variable won’t work in the global scope, since changing the “formats” attribute would the change every object.

You can discuss what you’re trying to achieve in #perl-openapi channel on the freenode IRC server or follow up with a comment here, but I won’t take the PR as it stands now.

When that is said: I’m more interested in two new issues that explains which email and uri formats is not supported, since that sounds like a bug that needs fixing. But make sure you’re not mixing up “iri” and “uri” first :)

rolosworld commented 5 years ago

When that is said: I’m more interested in two new issues that explains which email and uri formats is not supported, since that sounds like a bug that needs fixing. But make sure you’re not mixing up “iri” and “uri” first :)

Sorry, right now I don't remember exactly why I modified the "uri" format validator, I made the change a while back and didn't make a note of what issue I had.

About the reason I modified the "email" format validator, when using the default validator it says these emails are valid:

You can review + run the test.pl script I provided and confirm it. I don't know if those emails are valid rfc5322 emails, but these are changes I needed and I wasn't restricted by any specifications.