Posts

Showing posts from May, 2019

Spring MVC Custom Validation

Spring MVC Custom Validation - FAQ: Is it possible to integrate multiple validation string in one annotation? Answer: Yes, you can do this. In your validation, you will make use of an array of strings. Here's an overview of the steps. 1. Update CourseCode.java to use an array of strings 2. Update CourseCodeConstraintValidator.java to validate against array of strings 3. Update Customer.java to validate using array of strings --- Detailed Steps 1. Update CourseCode.java to use an array of strings Change the value entry to an array of Strings: // define default course code public String[] value() default {"LUV"}; Note the use of square brackets for the array of Strings. Also, the initialized value uses curley-braces for array data. 2. Update CourseCodeConstraintValidator.java to validate against array of strings Change the field for coursePrefixes to an array private String[] coursePrefixes; Update the isValid(...) method to loop through the course...

How to handle String input for for an Integer Field

Image
 How to Make Integer field required and handle Strings? Question: I am getting the following error when i submit the form with an empty value for customer "freePasses". I am  using @NotNull on the field "freePasses". It is not throwing "is required" after validation after submit. How to fix this? Please help. Also, how do I handle validation if the user enters String input for the integer field? ----- Answer: Great question! The root cause is the freePasses field is using a primitive type: int. In order to check for null we must use the appropriate wrapper class:  Integer . To resolve this, In Customer.java, replace "int" with "Integer" @NotNull(message="is required")    @Min(value=0, message="must be greater than or equal to zero")    @Max(value=10, message="must be less than or equal to 10")    private  Integer  freePasses; Then update your getter/setter methods to use "Integer"  ...

Validation Spring

When performing Spring MVC validation, the location of the BindingResult parameter is very important. In the method signature,  the BindingResult parameter must immediately after the model attribute . If you place it in any other location, Spring MVC validation will not work as desired. In fact, your validation rules will be ignored. @RequestMapping("/processForm") public String processForm( @Valid @ModelAttribute("customer") Customer theCustomer, BindingResult theBindingResult) { ... } Here is the relevant section from the Spring Reference Manual --- Defining @RequestMapping methods @RequestMapping handler methods have a flexible signature and can choose from a range of supported controller method arguments and return values. ... The  Errors  or  BindingResult  parameters have to follow the model object that is being bound immediately ... Source: https://docs....