0% found this document useful (0 votes)
28 views

Custom Validation & Read Property File Data-Spring

This document discusses how to load property files in Spring and use them for validation messages. It shows adding a MessageSource bean to load a Messages.properties file. It then defines validation messages for customer age. A CustomerValidator class is implemented to validate age is present and in the valid range. The RegistrationController uses the validator via an InitBinder rather than explicitly calling validate, so the custom validator will run automatically on form submit.

Uploaded by

madhavi u
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Custom Validation & Read Property File Data-Spring

This document discusses how to load property files in Spring and use them for validation messages. It shows adding a MessageSource bean to load a Messages.properties file. It then defines validation messages for customer age. A CustomerValidator class is implemented to validate age is present and in the valid range. The RegistrationController uses the validator via an InitBinder rather than explicitly calling validate, so the custom validator will run automatically on form submit.

Uploaded by

madhavi u
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Read property file(Messages.

properties) data: Add below code in Spring Configuration File,we can


directly use property file in our Class.

<bean id="messageSource" class=". .ReloadableResourceBundleMessageSource">

<property name="basename" value="/WEB-INF/messages" />

</bean>

Messages. Properties:

1. customer.age.empty = Age is required

2. customer.age.range.invalid = Age should be between 18 to 60

Custom Validation:

@Component

public class CustomerValidator implements Validator {

public void validate(Object target, Errors errors) {

Customer customer = (Customer)target;

int age = customer.getAge();

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "customer.age.empty");

//Business validation

if(age < 18 || age > 60){

errors.rejectValue("age", "customer.age.range.invalid");

}}

public class RegistrationController {

@Autowired

CustomerValidator customerValidator;
public String doLogin(@Valid Customer customer, BindingResult result,Model model) {

model.addAttribute("customer",customer);

customerValidator.validate(customer, result); //we can comment if we use Initbinder

if(result.hasErrors()){

return "register";

return "home";

In the controller class , add below code

@InitBinder

public void initBinder(WebDataBinder webDataBinder){

webDataBinder.setValidator(customerValidator);

And remove the below code which we make an explicit call to validate

customerValidator.validate(customer, result);

So InitBinder will call the custom validator automatically on form submit.

You might also like