开发者

JSF 2 reusing the validation defined in the JPA entities?

开发者 https://www.devze.com 2023-02-18 11:52 出处:网络
Let\'s start with an example : In my JPA entity public class User { @Pattern(\"^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$\", message=\"invalidEmailResou

Let's start with an example :


In my JPA entity

public class User {
    @Pattern("^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$", message="invalidEmailResourceBundleKey")
    private String email;

    @Min(5, message="minimumResourceBundleKey")
    private int age;

...
}

In my JSF Bean

开发者_高级运维
public class UserBean {
    private User user;

    // do i have to redefine it here, since it's already a part of the user ?
    @@Pattern("^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$") 
    public String getEmail() {
        return user.getEmail();
    }
    public void setEmail(String s) {
        user.setEmail(s);
    }

    // do i have to redefine it here, since it's already a part of the user ?
    @Min(5, message="minimumResourceBundleKey")
    public int getAge() {
        return user.getAge();
    }
    public void setAge(int age) {
        user.setAge(age);
    }
}

Is it possible to reuse the the validations for the entities for the JSF beans that actually delegates the method calls to the entities, so that i dont have to redefine the bean validations on the JSF beans ?

Can i even extend the reusing to the level of the error message in resource bundle, and whether the message can be parameterized with {0} etc like the usual ? I wonder if there's any example on the web for this, since i've been unable to find none.

Please share your thoughts on this ..

Thank you !


You don't need to redefine them if you don't unnecessarily flatten the bean properties. Just have a getUser() instead.

public class UserManager {

    private User user;

    public User getUser() {
        return user;
    }

}

And bind to the properties of the JPA entity directly.

<h:inputText value="#{userManager.user.email}" />
<h:inputText value="#{userManager.user.age}" />

Unrelated to the concrete problem, your email regex will fail for internationalized domain names (IDN) which are introduced last year. I'd fix the regex to not only accept latin characters. See also this answer for an example.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号