扩展ASP.NET验证 [英] Extending ASP.NET validators

查看:79
本文介绍了扩展ASP.NET验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想延长asp.net验证,这样我可以做一个验证器依赖于另一个。我的情况是,我们必须验证在一个文本框的日期。通常情况下,我只想用一个RequiredFieldValidator组合(确保日期提供),CompareValidator(以确保日期是一个日期),最后一个RangeValidator控件(确保日期是在要求的范围内)。

I want to extend the asp.net validators such that I can make one validator dependent on another. The situation I have is that we have to validate a date in a textbox. Normally I would just use a combination of a RequiredFieldValidator (to ensure the date is provided), CompareValidator (to ensure the date is a date) and finally a RangeValidator (to ensure the date is within the required limit).

这样做的问题是验证不依赖于对方,所以其结果是用户将看到可能在每进行一次验证所有的三个消息时真的所有我们希望他们看到的是最相关的信息,即如果他们在日期文本框中输入ABC这是不恰当的,以显示他们说的日期是不是在有效范围(即使在技术上,我想这是真的)。​​

The problem with this is that the validators do not depend on each other, so as a result the user would see possibly all three messages at once for each validator when really all we want them to see is the most relevant message, i.e. if they entered "abc" in the date text box it would not be appropriate to show them the message saying the date was not in the valid range (even though technically I suppose this is true).

目前要取决于什么验证失败提供这种功能,我们使用的CustomValidator,只是把服务器验证事件处理程序中的所有三个验证和更改编程错误消息。

Currently to provide this kind of functionality we use a CustomValidator and just put all three validations within the server validate event handler and change the error message programmatically depending on what validation failed.

我想,因为它发生了不少在此应用程序来规范这个多一点,我想,如果我可以让验证彼此依赖,这将解决这个问题,也使我们能够充分利用客户端的验证而不是做一个回发特别处理自定义验证。

I would like to standardize this a bit more as it happens quite a bit in this application, I figure if I can make the validators dependent on each other this will solve the problem and also allow us to make use of the client side validation rather than having to do a postback especially to handle the custom validation.

我们的想法是,如果一个验证器依赖于另一个,如果是主是有效的则取决于将执行正常的验证(EvaluateIsValid()),否则如果主验证为无效,那么其他相关的验证将是有效的

The idea is that if one validator is dependent on another if that "master" is valid then the depended will perform its normal validation (EvaluateIsValid()) otherwise if the master validator is not valid then the other dependent validators will be valid.

我已经从已经在框架内提供的各种验证程序控件继承想出了以下的解决方案。

I have come up with the following solution by inheriting from the various validator controls that already have been provided in the framework.

public class RequiredFieldDependentValidator : RequiredFieldValidator
{
    [Description("The validation control to depend on for determining if validation should occur")]
    public string ValidationControlToDependOn
    {
        get
        {
            object obj = ViewState["ValidationControlToDependOn"];
            if (obj != null) return (string) obj;
            return null;
        }
        set
        {
            Control control = FindControl(value);
            if (control is IValidator)
                ViewState["ValidationControlToDependOn"] = value;
            else
                throw new HttpException("ValidationControlToDependOn is not a validation control");
        }
    }

    protected override bool EvaluateIsValid()
    {
        IValidator validationControlToDependOn = FindControl(ValidationControlToDependOn) as IValidator;

        if(validationControlToDependOn != null)
        {
            return !validationControlToDependOn.IsValid || base.EvaluateIsValid();
        }

        return base.EvaluateIsValid();
    }

目前我刚才$ C $光盘,它的的RequiredFieldValidator,理想情况下,我想对所有验证程序都提供了这种功能,但我看不到的方式来做到这一点而不复制上述code到同级为每个类型的验证的,我想为这样,如果有,我将不得不回去改变这种code对每个单独的验证类型的任何问题,提供此功能。

Currently I have just coded it for the RequiredFieldValidator, ideally I would like to provide this functionality for all of the validators but I cannot see a way to do this without copying the above code into a similar class for each individual type of validator I want to provide this functionality for thus if there are any problems I'm going to have to go back and change this code on each validator type individually.

有没有一种方法,我可以集中这code,并很容易验证程序使用,而无需从头开始编写整个验证只是这样我就可以改变他们进一步向下行继承的类。

Is there a way I can "centralise" this code and have it easily used in the validators without having to write the entire validators from scratch just so I can change the class they inherit from further down the line.

干杯,

推荐答案

您可能想寻找到一个WebControlAdapter。

You might want to look into a WebControlAdapter.

基本上可以覆盖器WebControls一定的方法(有条件某些浏览器,如果需要,但在这里可以为所有)。

Basically allows you to override certain methods of webcontrols (conditionally for some browsers if need, but here can be for all).

在你的情况,你会想重写EvaluateIsValid方法,并检查控制对一个父验证任何依赖。

In your case, you would want to override the EvaluateIsValid method and check if the control has any dependency on a 'parent' validator.

作为一个例子,我们最近成立一个TextBox适配器呈现一个最大长度属性控制。

As an example, a TextBox adapter we recently created to render a 'maxlength' attribute to the control.

Public Class TextBoxAdapter
        Inherits WebControlAdapter

        Private ReadOnly Property TextBoxControl() As TextBox
            Get
                Return DirectCast(MyBase.Control, TextBox)
            End Get
        End Property

        Protected Overrides Sub RenderBeginTag(ByVal writer As System.Web.UI.HtmlTextWriter)
            If TextBoxControl.TextMode = TextBoxMode.MultiLine AndAlso TextBoxControl.MaxLength > 0 Then
                writer.AddAttribute("maxlength", TextBoxControl.MaxLength.ToString)
            End If

            MyBase.RenderBeginTag(writer)
        End Sub
    End Class

要使用它,只需在您App_Browsers文件目录,并设置创建一个.browser文件适配器有:

To use it, just create a .browser file in your App_Browsers directory and setup the adapter there:

<browsers>
    <browser refID="Default">
        <controlAdapters>
            <adapter controlType="System.Web.UI.WebControls.TextBox"
               adapterType="TextBoxAdapter" />
        </controlAdapters>
    </browser>
</browsers>

这仍停留在你的情况下,唯一的并发症是如何依赖验证存储,以使EvaluateIsValid能够访问这个目录。你可能会考虑像ONOF非渲染控制建议或者视图状态/曲奇/其他的存储机制。

The only complication that still remains in your case is how to store the dependent validator in order for the EvaluateIsValid to have access to this directory. You might consider a non-rendered control like Onof suggested or else Viewstate/Cookie/other storage mechanism.

这篇关于扩展ASP.NET验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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