ASP的验证 - 确定年龄范围内 [英] asp validator - determine if age is within range

查看:584
本文介绍了ASP的验证 - 确定年龄范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ASP验证,有没有办法来验证输入的出生日期是年龄范围内,比如5和22岁?

Using a asp validator, is there a way to verify the date of birth that is entered is within an age range, say 5 and 22 years old?

我目前做的asp:compareValidator和ASP:RangeValidator控件,但我需要添加范围验证的另一个层面反对在文本框中输入的值当前日期,通知年龄是允许的(5和22的范围之外岁只)

I currently do a asp:compareValidator and a asp:rangeValidator, but i need to add another level of range validation for current date against the value entered in the textbox to notify that the age is outside the range allowed (5 and 22 years old only)

谢谢
托尼

推荐答案

您可以使用一个ASP.NET的CustomValidator这一点。在ASP.NET code,添加以下控件:

You could use an ASP.NET CustomValidator for this. In your ASP.NET code, you add the following control:

<asp:CustomValidator runat="server" id="ageByDateCheck"
    ControlToValidate="txtDate"
    OnServerValidate="CheckAgeByDate"
    ErrorMessage="You are not between the ages of 5 and 22." />

而在你的code-的背后,你必须检查岁的新方法。

And in your code-behind, you'd have a new method for checking the age.

public void CheckAgeByDate(object source, ServerValidateEventArgs args)
{
    var date = DateTime.Parse(args.Value);
    args.IsValid = true; //Replace this with your age check algorithm.
}

修改
如果您正在寻找客户端验证,你就必须创造一些JavaScript做您的验证和控制的 ClientValidation指定它字段。所以,你的ASP.NET控件现在看起来是这样的:

EDIT If you're looking for client-side validation, you'll have to create some javascript to do your validation and specify it in the control's ClientValidation field. So your ASP.NET control now looks something like this:

<asp:CustomValidator runat="server" id="ageByDateCheck"
    ControlToValidate="txtDate"
    OnServerValidate="CheckAgeByDate"
    ClientValidation="ClientValidate"
    ErrorMessage="You are not between the ages of 5 and 22." />

您可能不必有一个不同的名字,但我倾向于让事情分开为code理智。

Your probably don't have to have a different name for that, but I tend to keep things separate for code sanity.

有关你的JavaScript:

For your javascript:

<script language="javascript"> 
function ClientValidate(source, arguments)
{
    var date = new Date(arguments.Value); //make sure it's something javascript can parse
    //validate age here
    arguments.IsValid = isValid(date);
}
</script>

这篇关于ASP的验证 - 确定年龄范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆