I am using SpringMVC in my webapp to handle forms and their validation.
In my Validator I have code like this:
@Override
public void validate(final Object target, final Errors errors)
{
final LoginCommand loginCommand = (LoginCommand) target;
if (checkCredentials(loginCommand.getLogin(), loginCommand.getPassword()) {
errors.rejectValue("login", "login.error.invalid");
errors.rejectValue("password", "login.error.invalid");
}
//..
This way I get the properly rendered invalid whenn filling the cssErrorClass attribute. Problem now is that the login.error.invalid message is in the error-message list I am going to display twice.
What is the best way to mark two input fields inva开发者_C百科lid, but only have one message in the error list? I searched the SpringMVC documentation/api all over and did not find a way to reject a field without supplying a message.
I suggest to mark all form as invalid in this case:
if (checkCredentials(loginCommand.getLogin(), loginCommand.getPassword()) {
errors.rejectValue("login.error.invalid");
}
And show it on view by
<form:errors />
Assuming
<%@ taglib uri="spring.tld" prefix="s"%> <%@ taglib uri="spring-form.tld" prefix="sf"%>
You must limit the sf:errors tag by placing it in a s:bind tag. Here is an example (the path is probabaly not correct for your needs, but is fine for this example) that limits the errors to the login field:
<s:bind path="loginForm.login"> <sf:errors/> </s:bind>
Note: I typed this directly into the answer and it's been a while since I used spring mvc.
精彩评论