簡體   English   中英

擴展RequiredFieldValidator

[英]Extending RequiredFieldValidator

您好我正在嘗試擴展requirefieldvalidator以獲取新屬性並驗證regularrexpressions。 我知道我可以使用RegularExpression控件,但后來我需要2個控件,所以我想要消除它,所以我只需要使用兩個控件。 我還想制作其他功能,包括我擴展它。

我的問題是我不知道要覆蓋什么 - 我嘗試了Validate()但我得到“無法覆蓋繼承的成員'System.Web.UI.WebControls.BaseValidator.Validate()',因為它沒有標記為虛擬,抽象,或覆蓋“我理解EvaluateIsValid()用於驗證控件而不是控件中的內容。

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace ClassLibrary
{
    public class RequiredFieldValidatorExtended : RequiredFieldValidator
    {
        public RequiredFieldValidatorExtended()
        {

        }

        private string _regEx;
        public string RegEx
        {
            get
            {
                return _regEx;
            }
            set
            {
                _regEx = this.RegEx;
            }
        }

        protected override bool EvaluateIsValid()
        {
            TextBox textBox = (TextBox)Page.Form.FindControl(ControlToValidate);
            if (textBox.Text != null && textBox.Text.Length > 0)
            {
                if (this._regEx != null && _regEx.Length > 0)
                {
                    if (Regex.IsMatch(textBox.Text, _regEx))
                        IsValid = true;
                    else
                        IsValid = false;
                }
                IsValid = true;
            }
            else
                IsValid = false;

            base.Validate();
            return IsValid;
        }
    }
}

我認為你應該使用CustomValidator或者從BaseValidator抽象類派生

http://msdn.microsoft.com/en-us/library/aa720677(v=vs.71).aspx

您應該覆蓋EvaluateIsValid()方法。 BaseValidator.Validate()方法在內部使用virtual EvaluateIsValid 例如:

protected override bool EvaluateIsValid()
{
    bool isValid = base.EvaluateIsValid();
    if (isValid)
    {
        string controlToValidate = this.ControlToValidate;
        string controlValue = GetControlValidationValue(controlToValidate);
        if (!string.IsNullOrWhiteSpace(controlValue))
        {
            if (this._regEx != null && _regEx.Length > 0)
            {
                if (Regex.IsMatch(controlValue, _regEx))
                    isValid = true;
            }
        }
    }


    return isValid;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM