简体   繁体   中英

Class Level validation in Spring Form

I am new to Spring and am trying to make a validation form with internationalized validation messages. I am using JSR @Valid annotation for my Login Form validation.

I want to perform the below 3 validations:

  1. Check if username is empty
  2. Check if password is empty.
  3. Check if password is valid against username.

I am able to perform all these validations but the problem is that on my UI, I am getting the 3rd validation along with 1st and 2nd validation.

I want to display 3rd validation only when 1st and 2nd validations are passed.

Below is my jsp code :

                <label for="username"> <spring:message code="label.email" />                        </label>
                <form:input path="username" id="username" />
                <form:errors path="username" style="color: red" />
                <br />
                <br />
                <label for="password"> <spring:message
                        code="label.password" /></label>
                <form:input path="password" id="password" />
                <form:errors path="password" style="color: red" />
                <br />
                <form:errors path="authenticated" style="color: red" />

My controller code :

@RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET})
public String authenticate(@ModelAttribute("user") @Valid User user,BindingResult result, ModelMap model, Locale locale, SessionStatus status, RedirectAttributes redirectAttrs, HttpServletRequest req){       

    if(result.hasErrors()){
        return "home";
    }

//code to validate password against username
}

My Bean Code

public class User implements Serializable {

private static final long serialVersionUID = -7788619177798333712L;

@NotEmpty(message = "Please enter your username.")
private String username;

@NotEmpty(message = "Please enter your password.")
private String password;

@AssertTrue(message= "Invalid username or password")
boolean authenticated;

It will be a big help if someone can guide me on this issue.

You can use class leven constraints rather than separate field for the validation.

See Cross field validation with Hibernate Validator (JSR 303) and How can I validate two or more fields in combination?

Just introduce your own annotation to check field combination in the validator class which implements Constraint or ConstraintValidator interfaces.

Then add the annotation to the form class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM