trebol-ecommerce / trebol-backend-monolith

Monolithic eCommerce backend web application that exposes a RESTful API.
MIT License
16 stars 21 forks source link

Parameterize regex patterns used for validation #101

Closed bglamadrid closed 2 years ago

bglamadrid commented 2 years ago

The PersonPojo class has two properties phone1 and phone2 that are annotated with a @Pattern. This means that whenever they have a value and are triggered for validation, they try to match specifically against this pattern: ^(((\\(\\+?[0-9]{3}\\))|(\\+?[0-9]{3})) ?)?[0-9]{3,4}[ -]?[0-9]{4}$ which may not be compatible with all phone numbers; I originally made it for numbers originating from Chile.

But most importantly, it is hard-coded, and if it doesn't match against certain phone numbers, it has to be changed in the .java class file.

Proposal

bglamadrid commented 2 years ago

Apparently, values used in annotations cannot be changed at runtime since they are compiled just like fields or methods.

So, well, Java Reflection can modify the value, here's an an answer that exemplifies this https://stackoverflow.com/questions/14268981/modify-a-class-definitions-annotation-string-parameter-at-runtime

But there's still another risk. Regular expressions themselves also need to be compiled before testing them against any string.

Does the implementation behind @Pattern compile the regex and then reuse it (probably)? Or does it compile a new one every time it has to validate the value (unlikely)?

Maybe I should find another way to validate these values through regex pattern.