go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.41k stars 1.3k forks source link

Efficient Regex Validation Integration #1115

Open yousifnimah opened 1 year ago

yousifnimah commented 1 year ago

Enhances

This pull request introduces an optimized version of the code that enables the validation of field values using custom regex patterns specified through tags. The improvements made to the code enhance efficiency, readability, and flexibility. The custom regex patterns can be easily associated with fields using tags, allowing for seamless validation based on specific requirements.

Here's a summary of the changes made:

Example of usage:

type User struct {
    Email string `validate:"required,email"`
    Phone string `validate:"required,regex=^[0-9]{10}$"`
}
coveralls commented 1 year ago

Coverage Status

coverage: 73.926% (-0.05%) from 73.972% when pulling 794024fdcb9976e838958eb3d99c5f2f29a2d057 on yousifnimah:master into bd1113d5c1901c5205fc0a7af031a11268ff13ee on go-playground:master.

deankarn commented 1 year ago

I will need to think about this, again, as in the documentation I explicitly state why I do not already have a regex validation, but to summarize a few points:

yousifnimah commented 1 year ago

Thank you for your response.

I have inspired this validation from Laravel regex validation and as developers we occasionally need to validate based on regex pattern, for example: validating custom date format or the country code.

Furthermore, regarding translation message I have added a general message for all supported languages which is "invalid format" and this message returns for any invalid case. We can pass a custom message from the definition of regex as a tag field.

However, I would like to contribute with this library and help to develop new features.

deankarn commented 1 year ago

@yousifnimah yep I understand and makes sense.

You can also do this today by registering a custom validation with tag that uses the Regex internals which may be more maintainable.

How do you propose to deal with the conflicting characters?

yousifnimah commented 1 year ago

@yousifnimah yep I understand and makes sense.

You can also do this today by registering a custom validation with tag that uses the Regex internals which may be more maintainable.

How do you propose to deal with the conflicting characters?

I've added a handler for comma representation and it would be like this:

// Replace any escaped backslashes before commas with a placeholder to avoid escaping.
// We'll replace them back later after compiling the regex pattern.
regexPattern = strings.ReplaceAll(regexPattern, `__comma__`, ",")

The usage in the struct tag:

Phone string `validate:"required,regex=^__comma__[0-9]{2}$"`

It represents this pattern:

Phone string `validate:"required,regex=^\,[0-9]{2}$"`

And it works fine.