如何在验证失败时更改输入字段和标签的css类? [英] How to change css class for the inputfield and label when validation fails?

查看:113
本文介绍了如何在验证失败时更改输入字段和标签的css类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个用户名来验证,在这种情况下,我需要显示用户名outputText和用户名inputText字段为红色,当验证失败以及错误消息。

Suppose I have a username to validate, in this case I need to show username outputText and username inputText field in red color when validation fails along with error message.

我试图在面板组中绑定所有这些,如果验证失败,所有字段都应该受到影响。但

I tried to bind all these in a panelgroup so that if validation fails all field should be affected. But simply putting panelgroup is not working.

我的支持bean验证器

My backing bean validator

public void emailValidate(FacesContext context,
        UIComponent componentToValidate,
        Object value)
        throws ValidatorException {


    String email = value.toString();


    if (!Validator.isEmailAddress(email))
    {
        FacesMessage message =
                new FacesMessage(FacesMessage.SEVERITY_ERROR,"Email","Please enter valid email address");
                throw new ValidatorException(message);
    }


}

My Jsf

<h:panelGroup>
<h:outputText value="Email"/>
<h:message for="emailInput/>
<h:inputText id="emailInput" value="#{mybean.email}" validator="#{mybean.emailValidate}"/>
</h:panelGroup>


推荐答案

通过 binding 属性将输入组件绑定到视图,它将作为 UIInput 组件引用,以便您可以使用< a href =http://docs.oracle.com/javaee/6/api/javax/faces/component/UIInput.html#isV​​alid%28%29 =nofollow> UIInput# styleClass 属性中的isValid()

Bind the input component to the view via binding attribute. It'll become available as an UIInput component reference in EL, so that you can use UIInput#isValid() in styleClass attribute.

<h:outputLabel for="emailInput" value="Email" 
    styleClass="#{emailInput.valid ? '' : 'error'}" />

<h:inputText id="emailInput" binding="#{emailInput}" ... 
    styleClass="#{emailInput.valid ? '' : 'error'}" />

要成为真实标签;还请注意,您不需要根据cubbuk的回答建议创建一些bean属性)

(note that I fixed your label to be a real label; also note that you don't need to create some bean property at all as suggested by the answer of cubbuk)

是的,这可能会产生一些非 DRY 样板代码视图,您可以使用阶段监听器或系统事件监听器,您也可以使用 OmniFaces < o:highlight> 这个组件透明地执行所有的工作,参见现场演示

Yes, this may produce quite some non-DRY boilerplate code in the view. You can abstract this away with a phase listener or a system event listener. You can also use OmniFaces <o:highlight> component which does all the job transparently. See also the live demo.

这篇关于如何在验证失败时更改输入字段和标签的css类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆