【问题标题】:Is there how to validate into rich:calendar if the date selected is before a specific date?如果选择的日期在特定日期之前,是否有如何验证丰富:日历?
【发布时间】:2011-06-22 20:03:37
【问题描述】:

我有这个组件:

<rich:calendar enableManualInput="true" value="#{home.born}" datePattern="dd/MM/yyyy" />

我需要验证所选日期是否等于或早于此刻的实际日期... 有没有办法只用 rich:calendar 或者我必须在家里验证它?

问题解决了!我使用了 Balusc 提供的解决方案。 谢谢大家! :)

【问题讨论】:

    标签: jsf richfaces


    【解决方案1】:

    要在服务器端验证它,您可以使用Validator

    <rich:calendar ...>
        <f:validator validatorId="notAfterToday" />
    </rich:calendar>
    

    @FacesValidator("notAfterToday")
    public class NotAfterTodayValidator implements Validator {
    
        @Override
        public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            Date date = (Date) value;
            Date today = new Date();
    
            if (date.after(today)) {
                String message = "Date may not be later than today.";
                throw new ValidatorException(new FacesMessage(message));
            }
        }
    
    }
    

    【讨论】:

    • 这仅在使用日历图标选择日期时执行客户端验证。输入日期会绕过客户端验证。
    【解决方案2】:

    您应该能够使用 JavaScript 来做到这一点(所以在客户端)。如果查看Client API doc,可以看到rich:calendar 组件提供了getCurrentDate() JavaScript 函数。

    因此,您要做的是在 JavaScript 事件 ondateselectedoninputchange 上启动一个 JavaScript 函数,该函数将使用 getCurrentDate() 方法并与当前日期进行比较。

    类似的东西(我没有测试):

    <h:form id="myForm">
        ...
        <rich:calendar id="myCalendar" enableManualInput="true" value="#{home.born}" datePattern="dd/MM/yyyy"
            ondateselected="checkDate();" oninputchange="checkDate();"/>
        ...
    

    <script type="text/javascript">
    function checkDate() {
        var choosenDate = $("myForm:myCalendar").component.getCurrentDate();
        var now = new Date();
        // Calculate the difference between the 2 dates.
        // This method may be modified if you want to only compare date (i.e. not time).
        var diff = choosenDate.getTime() - now.getTime();
        if (diff < 0) {
            // choosenDate is before today
            alert("Error in the selected date!");
            // Do what you want here...
        }
    }
    </script>
    

    【讨论】:

    • 好的,但是我要保持日期不变吗?比如如果它不是一个有效的日期并且我想保留旧的值,接下来我应该怎么做验证?
    猜你喜欢
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    相关资源
    最近更新 更多