我有两个文本框,txtStartDate,txtEndDate,允许用户以格式(dd / mm / yyyy)选择日期。我需要能够创建一个验证器,检查这两个用户选择日期之间的天数是否为45天或更短。我可以使用其中一个Validator控件(如Range或Compare),还是必须创建自定义验证器?任何例子都会非常有用。
答案 0 :(得分:1)
您可以使用CustomValidator
:
<asp:CustomValidator id="StartEndDiffValidator"
ValidateEmptyText="true"
ClientValidationFunction="StartEndValidate"
OnServerValidate="StartEndValidate"
Display="Dynamic"
ErrorMessage="Timespan between start and end must be exactly 45 days"
runat="server"/>
This answer会引导您转到ClientValidationFunction
。
始终实施服务器端验证:
void StartEndValidate(object source, ServerValidateEventArgs args)
{
DateTime startDate;
DateTime endDate;
bool isStartDate = DateTime.TryParse(txtStartDate.Text, out startDate);
bool isEndDate = DateTime.TryParse(txtEndDate.Text, out endDate);
if(isStartDate && isEndDate)
{
int days = (endDate - startDate ).Days;
args.IsValid = days == 45;
}
else
{
args.IsValid = false;
}
}
您还可以CompareValidators
将Operator
属性设置为ValidationCompareOperator.DataTypeCheck
,Type =日期,以确保在两者中输入日期。
答案 1 :(得分:0)
试试这个块:
Dim st As String = txtClientSerStartTime.Text
Dim et As String = txtClientSerEndTime.Text
Dim time1 As DateTime
DateTime.TryParse(st, time1)
Dim ts1 As New TimeSpan(time1.Hour, time1.Minute, time1.Second)
Dim time As DateTime
DateTime.TryParse(et, time)
Dim ts As New TimeSpan(time.Hour, time.Minute, time.Second)
Dim dur As TimeSpan = ts - ts1
Dim unit As Decimal = dur.Hours
If unti = 45 Then
'do something'
Else
'do something'
End If