Question

I am able to validate form and display Spring validation error with Spring form tag. Instead of displaying as HTML markup how can I display those errors using jQuery Noty Plugin?

Controller:

   @RequestMapping(value = "/Register", method = RequestMethod.POST)
public ModelAndView Registeruser(@ModelAttribute("registerBean") @Valid RegisterBean registerBean, BindingResult bindingResult) {
    ModelAndView mv = new ModelAndView();
    if (bindingResult.hasErrors()) {
        mv.setViewName("index");
        mv.addObject(registerBean);
    } else {
        boolean registered = userservice.RegisterUser(registerBean);
        if (registered) {
            List<SimpleGrantedAuthority> authList = new ArrayList<SimpleGrantedAuthority>(1);
            authList.add(new SimpleGrantedAuthority("ROLE_USER"));
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(registerBean.getEmail(), registerBean.getPassword(), authList);
            SecurityContextHolder.getContext().setAuthentication(auth);
            mv.setViewName("auth/Home");
        } else {
            mv.setViewName("index");
        }
    }
    return mv;
}
Was it helpful?

Solution

You didn't mention which view technology you are using. I assume that JSP is in use.

First you should render any error message into a separate hidden container. In this example product is my modelAttribute. It is completely up to you what you are showing to your users in case of an error. In this example a unordered list of validation type on property and validation message will be shown.

<%@ taglib prefix="s" uri="http://www.springframework.org/tags"%>

<s:hasBindErrors name="product">
    <div id="error-noty" style="display:none;">
        <h3>You have errors in your input!</h3>
        <ul>
            <c:forEach items="${errors.fieldErrors}" var="error">
                <li>${error.codes[1]} ${error.defaultMessage}</li>
            </c:forEach>
        </ul>
    </div>
</s:hasBindErrors>

Then you should initialize noty only if a container with the selector #error-noty could be found in the page. Hand over the html from the hidden container to noty and you're done.

<script>
    var errors = $('#error-noty');
    if(errors.html()) {
        noty({text: errors.html()});
    }
</script>

A working example can be found here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top