ASp:NET如何在客户端执行日期差异验证?

时间:2016-09-20 19:47:04

标签: javascript jquery custom-validators

我需要验证输入,因此Date1和Date2之间的差异不超过30天。

我试图在asp.net中使用自定义验证,但不确定在我的情况下它是否是正确的选择。

我有以下html

.
.
.
 <tr>
    <td>
        <asp:Label ID="lblFileDate" runat="server">File Date: from</asp:Label>
    </td>
    <td>
        <asp:TextBox ID="txtDateFrom" runat="server" CssClass="datepicker1"></asp:TextBox>    
        <asp:RequiredFieldValidator ID="rfvDateFrom" runat="server" ControlToValidate="txtDateFrom" ForeColor="Red" ErrorMessage="Date From is Required" ValidationGroup="vgForm" >*</asp:RequiredFieldValidator>
    </td>
    <td style="padding-left:40px; text-align:right;">
        <asp:Label ID="lblDateTo" runat="server" >to:</asp:Label>
    </td>
    <td width="165">
        <asp:TextBox ID="txtDateTo" runat="server" colspan="2" CssClass="datepicker2"></asp:TextBox>   
        <asp:RequiredFieldValidator ID="rfvDateTo" runat="server" ControlToValidate="txtDateTo" ForeColor="Red" ErrorMessage="Date To is Required" ValidationGroup="vgForm" >*</asp:RequiredFieldValidator> 
        <asp:CustomValidator ID="cstDateValidation" runat="server" ErrorMessage="Date difference should not be more then 30 days" ClientValidationFunction="ValidateDateDiff"></asp:CustomValidator>
    </td>
</tr>
 <tr>
        <td style="text-align: right;" colspan="4">
            <asp:Button id="btnSearch" Text="Search" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" runat="server"  
            CausesValidation="true" CommandName="Search" OnCommand="btnSearch_Click" OnClientClick="return ValidateFields()" />
        </td>
</tr>
.
.
.

<div id="errorDisplay">
     <asp:ValidationSummary ID="vSum" runat="server" ShowSummary="true" ValidationGroup="vgForm"></asp:ValidationSummary>   
</div>

这是我的javascript

function ValidateFields() {

    var isValid = false;

    isValid = Page_ClientValidate('vgForm');
        if (!isValid) {
            $('#errorDisplay').dialog({
                title: "Validation Error",
                modal: true,
                resizable: false,
                width: 250,
                buttons: {
                    Close: function () {
                        $(this).dialog('close');
                    }
                }
            });
            return false;
        }
        return true;
    }

function ValidateDateDiff(sender, args) {
        var dateFrom = $('#cphBody_Cnt_txtDateFrom').val();
        var dateTo = $('#cphBody_Cnt_txtDateTo').val();

        var diff = dateFrom - dateTo;
        if (diff > 30) {
           args.IsValid = false;
        }        
}

做这样的事情的最佳方式是什么?

0 个答案:

没有答案