次の方法で共有


正規表現検証コントロールのサンプル

ここで示す正規表現検証コントロールは、「基本検証コントロールのサンプル」で説明する基本検証コントロールを拡張します。この検証コントロールは、次の機能を基本検証コントロールに追加します。

  • 正規表現をユーザー (ページ開発者) が指定するための、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

参照

検証コントロールのサンプル | 基本検証コントロールのサンプル | 必要なフィールド検証コントロールのサンプル | 検証コントロールのスクリプト ライブラリのサンプル | 検証コントロール構成ファイルのサンプル | 検証コントロールのテスト ページのサンプル | 検証コントロールの開発