简体   繁体   中英

custom validator for last day of a month - c#

I'm new to asp.net, so plz bear with me: I want to create a custom validator to check if the input date given in a textbox (which has a calendar extension(AJAX)) is the last day of a month or not. Here is what I tried to do:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs e)
{

    DateTime dt = Convert.ToDateTime(e.ToString("dd/MMM/yyyy"));
    DateTime lastOfMonth = new DateTime(dt.Year, dt.Month, 1).AddMonths(1).AddDays(-1);
    if (dt == lastOfMonth)
    {
        e.IsValid = true;
    }
    else
    {
        e.IsValid = false;
    }

}

I think the problem is the way I'm handling the object 'e'. Any help is greatly appeciated. Thanks a lot in advance!

You are right. e is not the date, it is an instance of ServerValidateEventArgs . You should get the Value property from there. Value is a string, that you will need to convert to a date time, then do your validation.

DateTime dt;
if (DateTime.TryParseExact(e.Value, "dd/MMM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt)) 
{
    // validation of dt here.
}

You will need to know the format the date is expected to be in an parse that, so I suggest to use DateTime.TryParseExact . You will also need to pass in the correct culture, that the date is formatted in, since parsing rules depend on that - especially in this case where you have MMM as part of the pattern, because that will be different between cultures.

In general you should use the TryParse family of methods when parsing dates or numbers that come from user input. These will not throw on a failure, but return false. If the return value is false, the parsing failed, in that case you should fail validation.

I have some extension methods which you could take a look at which will allow you to return the last day of the month and compare the two dates...

they are open source... http://zielonka.codeplex.com/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace zielonka.co.uk.extensions.system
{
    //DateTime lastDay = DateTime.Now.GetLastDateTimeOfMonth();

    public static partial class DateTimeExtensions
    {
        public static DateTime GetLastDateTimeOfMonth(this DateTime dateTime)
        {
            return new DateTime(dateTime.Year, dateTime.Month, 1).AddMonths(1).AddDays(-1);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM