Shams
Shams

Reputation: 3687

JSR 303 Bean Validation in Spring

here is my formbean:-

public class LoginFormBean {

    @NotEmpty
    private String userId;

    @NotEmpty
    private String password;    

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String pass) {
        this.password = pass;
    }
}

and in my message.properties file i write:-

NotEmpty={0} must not empty.

It shows me error message as: userId must not empty. and password must not empty.

But i want to show error message as User Id must not empty. or 'Password must not empty.'

I know i can use @NotEmpty(message="User Id must not empty") in my formBean but i want synchronize message as if we need to change message, it will be less overhead.
I have searched the JSR docs but not find any thing to replace my attribute name userId to User Id on fly. Please guys help me, stuck in it from two days.
If it is not possible then tell me or if not then help me in something alternative.

Thanks
Shams

Upvotes: 3

Views: 2947

Answers (3)

Amit Patel
Amit Patel

Reputation: 15985

For reference, just log the BeanPropertyBindingResult instance and check the log. You would find four different types property codes for each property violating validations.

Here is a sample log for reference

Field error in object 'member' on field 'name': rejected value []; codes [NotEmpty.member.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [member.name,name]; arguments []; default message [name]]; default message [may not be empty]

In above log you can find codes [NotEmpty.member.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]

When you don't configure any error codes or spring doesn't find matching code then spring brings DefaultMessageCodesResolver in action to resolve error message. Check java doc to see the format of additional error codes.

Upvotes: 0

roghughe
roghughe

Reputation: 169

You've probably fixed this by now, but to set up error messages on JSR 303 formbeans you need to add entries to your property file in the following format:

<Constraint-Name>.<formbean-name>.<attribute-name>=My Message Text

In your case that will be:

NotEmpty.loginFormBean.userId=User Id must not empty

NotEmpty.loginFormBean.password=Password must not empty

where loginFormBean is the name of your form and not the class name.

Upvotes: 4

datum
datum

Reputation: 31

in the same message.properties file you can just add the following:

userId=User Id
password=Password

or you can use a separate file for field names and separate file for validation message codes. This will be just more readable.

Good Luck :)

Upvotes: 0

Related Questions