Pergunta

Hello I'm trying to extend the requirefieldvalidator to take a new property and validate regularexpressions also. I know I can use the RegularExpression control but then i need 2 controls so i want to eliminate it so i only have to use two controls. There are also other features i want to make which include me extending it.

My problem is i don't know what to override - i tried the Validate() but i get "cannot override inherited member 'System.Web.UI.WebControls.BaseValidator.Validate()' because it is not marked virtual, abstract, or override" and i understand the EvaluateIsValid() is for validating the control not what is in the control.

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;
        }
    }
}
Foi útil?

Solução

I think you should use CustomValidator instead or derive from BaseValidator abstract class

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

Outras dicas

You should override EvaluateIsValid() method. BaseValidator.Validate() method uses virtual EvaluateIsValid internally. E.g.:

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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top