ansman/validate.js

Question: optional fields with regex or email validation

Closed this issue · 1 comments

I'm attempting to implement a rather complex validation based on externally delivered data.
We have specific business rules where a value is optional, but if it's delivered, it should adhere to a regex.

What I've tried now is combining presence and format like so:
{ "optionalValue": { "presence": false, "format": { "pattern": "^([a-zA-Z0-9]|[-._]){2,49}$", "flags": "i", "message": "'%{value}' does not match regex" } } }

What I'm trying to accomplish: In this example, a value can be empty, but if a value is delivered it should be between 3 and 50 chars.

However, it seems that presence is ignored and empty values are considered faulty.
The same happens for email, so it's not directly related to the regex.

What would be the best approach for this? I have 500+ different fields to validate, of different types, so I would like to avoid overhauling my constraints half-way through.

Update: I've solved this.
For future generations: I switched CSV parsers and overlooked that the new implementation used empty strings. By doing a deep-replace on the input data from all values with empty string to nulls, the validation works as expected.