spring custom validator example with Validator interface



Spring controller with @Validated annotation

package com.candidjava.spring.controller;

import javax.validation.Validation;
import javax.validation.ValidatorFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import com.candidjava.spring.bean.User;

@Controller
public class UserController {
User users = new User();

@Autowired
@Qualifier("userValidator")
private Validator validator;

@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}

@GetMapping("index")
public ModelAndView register(User user) {
return new ModelAndView("register");
}

@PostMapping("/register")
public ModelAndView create(@Validated User user, BindingResult bindingResult) throws NoSuchMethodException, SecurityException {

ModelAndView model = new ModelAndView("view");
// user bean will be automatically binded to view refer @ModelAttribute
ValidatorFactory vf= Validation.buildDefaultValidatorFactory();
javax.validation.Validator validator = vf.getValidator();
validator.validate(user);

if(bindingResult.hasErrors())
{
return new ModelAndView("register");
}
users.setName(user.getName());
users.setEmail(user.getEmail());
users.setGender(user.getGender());
users.setLanguage(user.getLanguage());
users.setCountry(user.getCountry());
users.setPassword(user.getPassword());
users.setPhone(user.getPhone());
return model;
}

@GetMapping("/register")
public ModelAndView viewData(User user) {

ModelAndView model = new ModelAndView("register");
return model;
}
}

Implementing spring Validator interface

package com.candidjava.spring.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.candidjava.spring.bean.User;

public class UserCustomValidation implements Validator{
@Override
public boolean supports(Class<?> userClass) {
return User.class.equals(userClass);
}

@Override
public void validate(Object target, Errors errors) {

User user = (User) target;
if(!(user.getName().matches("[a-zA-Z ]*$")))
{
errors.rejectValue("name", "symbolsPresent",new Object[]{"'name'"},"name can't be symbols");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "name.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "password.required");
ValidationUtils.rejectIfEmpty(errors, "gender","gender.required");
ValidationUtils.rejectIfEmpty(errors, "country","country.required");
ValidationUtils.rejectIfEmpty(errors, "language","language.required");
ValidationUtils.rejectIfEmpty(errors, "phone","phone.required");
ValidationUtils.rejectIfEmpty(errors, "email","email.required");

}

}


Spring ReloadableResourceBundleMessageSource and Validator Bean configuration

package com.candidjava.spring.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.validation.Validator;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.candidjava.spring.validator.UserCustomValidation;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.candidjava.spring.controller")
public class SpringConfiguration {

@Bean(name="jspViewResolver")
public ViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();

viewResolver.setPrefix("WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}

@Bean
public ReloadableResourceBundleMessageSource messageSource()
{
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:message");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;

}

@Bean
public Validator userValidator()
{
Validator bean = new UserCustomValidation();
return bean;
}
}

Spring resource file

name.required=Name field can't be blank
gender.required=Please specify your gender
language.required=Please select at least one language
country.required=Please select your country
password.required=Password field can't be blank
email.required=Email field can't be blank
phone.required=Phone field can't be blank


Refer

    Spring 4 maven dependency

    Spring 4 Java based configuration



Screenshot



Download

            Spring 4 form validator example war

            Spring 4 form validator example maven zip



Related Post

Comments


©candidjava.com