简体   繁体   English

如果日期分为多个字段,如何使用比较验证器作为日期?

[英]How to use Compare Validator for dates if the date is split in several fields?

I am finishing a form in C#, and I would like to validate the data entry. 我正在用C#完成一个表格,我想验证数据输入。 I have seen numerous posts about validating with "CompareValidator". 我看过许多有关使用“ CompareValidator”进行验证的帖子。 That's fine and clear. 很好,很清楚。

I just would like to ask about a twist: I have the date in one field, result of using the AjaxControlToolkit Calendar Extender. 我只想问一个问题:我在一个字段中输入了日期,这是使用AjaxControlToolkit Calendar Extender的结果。 You can retrieve it as: 您可以将其检索为:

DateField.Text;

Then I have the hour in another field of the form, using MKB Time Select package from NuGet. 然后,使用NuGet的MKB Time Select软件包在表单的另一个字段中输入小时。

TimeSelector1.Hour + ":" + TimeSelector1.Minute

is the value I want to use. 是我要使用的值。

So the user has been filling the form, and picked a date from the date field, and an hour from the time selector. 因此,用户一直在填写表单,并从日期字段中选择了一个日期,并从时间选择器中选择了一个小时。 I want to check if the date and time that the user selects in these fields, is at least 24 hours greater than the current time, so it means the validator needs to use these two different fields to grab the initial data. 我想检查用户在这些字段中选择的日期和时间是否比当前时间至少大24小时,因此这意味着验证者需要使用这两个不同的字段来获取初始数据。

I am a bit confused about how would I get started about that. 我对如何开始对此感到困惑。

Basically, the validator should show the warning if 基本上,验证器应在以下情况下显示警告:

DateField.Text + " " + TimeSelector1.Hour + ":" + TimeSelector1.Minute

is greater than 大于

DateTime.Now.AddHours(24)

But I don't see clear how to tell the validator to validate this sort of statements, rather than the plain content on the fields. 但是我不清楚如何告诉验证器验证这种语句,而不是字段中的简单内容。

With the information provided, you should be able to parse your values into a DateTime object. 使用提供的信息,您应该能够将值解析为DateTime对象。

string dateString = String.Format("{0} {1}:{2}:00", DateField.Text, TimeSelector1.Hour, TimeSelector1.Minute);
DateTime selectedDateTime = new DateTime();
if (DateTime.TryParse(dateString, out selectedDateTime))
{
    if (selectedDateTime > DateTime.Now.AddHours(24))
    {
        // code
    }
}

At first you should parse your date and time strings into DateTime object then compare it with DateTime.Now.AddHours(24) 首先,您应该将日期和时间字符串解析为DateTime对象,然后将其与DateTime.Now.AddHours(24)进行比较。

    var inputDate = "20150606 10:12";
    DateTime date;
    if (!DateTime.TryParseExact(inputDate, "yyyyMMdd HH:mm" , CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
    {
        //datetime has invalid format
    }
    else
    {
        if(date > DateTime.Now.AddHours(24))
        {
            //show warning
        }
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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