We have fields: currency, amount, customerId. Let's think that our users input currencies can be USD, GBP, EUR. For USD we have to check amount (should be less than 1000) and customerId by regex. For GBP we only check customerId by regex. For EUR we only check amount.
Is switch(currency) and if statements okay for checking validations?
CodePudding user response:
If you are using spring boot, I suppose that using annotation base validation is the cleanest and the most readable way. Use @Max(value=1000) for amount and also @Pattern for regex validation.For currencies, I suggest using Enum and handling Exception. For the situation EUR you can see this: https://stackoverflow.com/a/2783859/11072063[1]
CodePudding user response:
I would recommend looking into Java Bean Validation via Hibernate Validator.
Baeldung has a great tutorial on how to use validation inside of Spring-Boot.
When writing your validation I would urge you to consider the following validation levels:
- Required, does the value have to exist.
- Type, is the value of the right type? Meaning is it a string, boolean, or integer?
- Date, does the value meet certain criteria? Is the value large enough, long enough, complex enough, etc...
- Does the value meet any requirements that are associated with the database? Does the value have to be unique or does the value have to exist already in the database?
I wrote a fairly detailed answer a while ago that might be of use: How to perform custom validations in Spring MVC?
CodePudding user response:
Since you have tagged Spring and Springboot and asked for cleanest way to validate user inputs, I would suggest Spring aop.
You can have a Validation Aspect.
This keeps your business logic clean with validation logic separated from it.