共用方式為


規則運算式驗證器控制項範例

此處說明的規則運算式驗證器控制項可以擴充基底驗證器控制項範例中所述的基底驗證器控制項。這個驗證器會將下列的功能加入基底驗證器。

  • 它會公開名為 ValidationExpression 屬性以允許使用者 (網頁開發人員) 指定規則運算式。
  • 它會覆寫 EvaluateIsValid 方法 (定義為 BaseDomValidator 中的抽象方法) 以提供邏輯來決定要驗證的欄位是否需符合規則運算式指定的模式。
  • 它會覆寫 AddAttributesToRender (繼承自 WebControl) 以提供評估邏輯的用戶端處理常式。用戶端處理常式是定義於指令碼程式庫中的函式。

若要編譯和建置這個範例,請參閱驗證器控制項範例中的說明。如需伺服器控制項的用戶端指令碼概觀,請參閱伺服器控制項中的用戶端功能

// RegexDomValidator.cs.
namespace DomValidators {

    using System.ComponentModel;
    using System.ComponentModel.Design;
    using System.Diagnostics;
    using System.Text.RegularExpressions;
    using System.Drawing.Design;
    using System;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    [
    ToolboxData("<{0}:RegexDomValidator runat=server ErrorMessage=\"RegexDomValidator\"></{0}:RegexDomValidator>")
    ]
    public class RegexDomValidator : BaseDomValidator {

        [
        Bindable(true),
        Category("Behavior"),
        DefaultValue(""),
        Editor("System.Web.UI.Design.WebControls.RegexTypeEditor,System.Design", typeof(UITypeEditor)),
        Description("ValidationExpression")
        ]                                         
        public string ValidationExpression {
            get { 
                object o = ViewState["ValidationExpression"];
                return((o == null) ? String.Empty : (string)o);
            }
            set {
                try {
                    Regex.IsMatch("", value);
                }
                catch (Exception e) {
                    //Throw new HttpException.
                    //                       HttpRuntime.FormatResourceString(SR.Validator_bad_regex, value), e);
                    throw new HttpException("Bad Expression", e);
                }
                ViewState["ValidationExpression"] = value;
            }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer) {
            base.AddAttributesToRender(writer);
            if (RenderUplevel) {
                writer.AddAttribute("evaluationfunction", "RegularExpressionValidatorEvaluateIsValid");
                if (ValidationExpression.Length > 0) {
                    writer.AddAttribute("validationexpression", ValidationExpression);
                }
            }
        }            

        protected override bool EvaluateIsValid() {

            // Validation always succeeds if input is empty or value was not found.
            string controlValue = GetControlValidationValue(ControlToValidate);
            Debug.Assert(controlValue != null, "Should have already been checked");
            if (controlValue == null || controlValue.Length == 0) {
                return true;
            }

            try {
                // Looking for an exact match, not just a search hit.
                Match m = Regex.Match(controlValue, ValidationExpression);
                return(m.Success && m.Index == 0 && m.Length == controlValue.Length);
            }
            catch {
                Debug.Fail("Regex error should have been caught in property setter.");
                return true;
            }
        }

    }
}
[Visual Basic]
' RegexDomValidator.vb
Option Explicit
Option Strict

Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Diagnostics
Imports System.Text.RegularExpressions
Imports System.Drawing.Design
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace DomValidators
   <ToolboxData("<{0}:RegexDomValidator runat=server ErrorMessage=""RegexDomValidator""></{0}:RegexDomValidator>")> _
   Public Class RegexDomValidator
      Inherits BaseDomValidator

      <Bindable(True), _
         Category("Behavior"), _
         DefaultValue(""), _
         Editor("System.Web.UI.Design.WebControls.RegexTypeEditor,System.Design", _
         GetType(UITypeEditor)), _
         Description("ValidationExpression")> _
      Public Property ValidationExpression() As String
         Get
            Dim o As Object = ViewState("ValidationExpression")
            If o Is Nothing Then
               Return String.Empty
            Else
               Return CStr(o)
            End If
         End Get
         Set
            Try
               Regex.IsMatch("", value)
            Catch e As Exception
               'Throw new HttpException.
               '                       HttpRuntime.FormatResourceString(SR.Validator_bad_regex, value), e);
               Throw New HttpException("Bad Expression", e)
            End Try
            ViewState("ValidationExpression") = value
         End Set
      End Property
      
      Protected Overrides Sub AddAttributesToRender(writer As HtmlTextWriter)
         MyBase.AddAttributesToRender(writer)
         If RenderUplevel Then
            writer.AddAttribute("evaluationfunction", "RegularExpressionValidatorEvaluateIsValid")
            If ValidationExpression.Length > 0 Then
               writer.AddAttribute("validationexpression", ValidationExpression)
            End If
         End If
      End Sub
      
      Protected Overrides Function EvaluateIsValid() As Boolean
         ' Always succeeds if input is empty or value was not found.
         Dim controlValue As String = GetControlValidationValue(ControlToValidate)
         Debug.Assert( Not (controlValue Is Nothing), "Should have already been checked")
         If controlValue Is Nothing Or controlValue.Length = 0 Then
            Return True
         End If
         Try
            ' Looking for an exact match, not just a search hit.
            Dim m As Match = Regex.Match(controlValue, ValidationExpression)
            Return m.Success And m.Index = 0 And m.Length = controlValue.Length
         Catch
         End Try
      End Function
   End Class
End Namespace

請參閱

驗證器控制項範例 | 基底驗證器控制項範例 | 必要欄位驗證器控制項範例 | 驗證器的指令碼程式庫範例 | 驗證器組態檔範例 | 驗證器測試網頁範例 | 開發驗證器控制項