2011-03-16 57 views
0

你好,我試圖擴展requirefieldvalidator採取一個新的屬性和驗證regularexpressions也。我知道我可以使用RegularExpression控件,但然後我需要2個控件,所以我想消除它,所以我只需要使用兩個控件。還有其他我想做的功能,包括我擴展它。我試圖驗證(),但我得到「不能重載繼承成員'System.Web.UI.WebControls.BaseValidator.Validate()',因爲它不標記虛擬,抽象或覆蓋「,我明白了EvaluateIsValid()用於驗證控件,而不是控件中的內容。Extending RequiredFieldValidator

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; 
     } 
    } 
} 

回答

1

您應該重寫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; 
} 
以下ControlPropertiesValid,EvaluateIsValid和的OnPreRender
+0

但是這不正是香港專業教育學院一直試圖從BaseValidator首要 – 2011-03-16 12:03:22

+0

@ 0BM:是的,這是你試過的方法。我只是試圖回答你的問題:'我的問題是我不知道要重寫什麼'和'我明白了EvaluateIsValid()是用於驗證控件,而不是控件中的內容。你也說過我的例子不起作用 - 你能解釋一下嗎? – Alex 2011-03-16 12:46:11