日期验证器,无法在C#中选择旧日期和今天的日期 [英] date validator that cannot choose old date and today date in c#
问题描述
当用户在文本框中插入所选日期时,该日期不能是旧日期或今天的日期,我可以使用什么验证规则?
When user insert the selected date in the textbox the date cannot be an old date or today date what is validation rule i can use?
我不确定要使用哪个验证器控件.
i am not sure which validator control to use either.
推荐答案
一种方法是将 CustomValidator
与 ServerValidate
一起使用,如下所示:
One way is using a CustomValidator
with a ServerValidate
like this:
<asp:CustomValidator runat="server"
ID="CustDateValidator"
ControlToValidate="txtDate"
onservervalidate="CustDateValidator_ServerValidate"
ErrorMessage="enter valid date in the future" />
隐藏代码:
protected void CustDateValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt > DateTime.Today);
}
您还可以提供 <如果需要的话,可以使用code> ClientValidationFunction (具体实现由您决定).
You can also provide a ClientValidationFunction
if you want(implementation is up to you).
注意:如果输入控件为空,则不会调用任何验证函数,并且验证成功.
Note: If the input control is empty, no validation functions are called and validation succeeds.
如果您需要确保它不为空,那么您还需要一个 RequiredFieldValidator
.
If you need to ensure that it's not empty then you'll need a RequiredFieldValidator
too.
这篇关于日期验证器,无法在C#中选择旧日期和今天的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!