2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C# Windowsフォームで入力制限、チェックを正規表現で行う

Last updated at Posted at 2022-12-13

1. はじめに

  • C# Windowsフォームで正規表現で入力チェックをしたい
  • エラーが発生した場所、発生内容をポップアップで分かるようにしたい

2. 開発環境

  • Visual Studio 2022
  • .NET6
  • Windows10

3. 動作イメージ

  • 数字以外を入力するとテキストボックスに反映されない
    image.png

  • Checkボタンをクリックすると、エラーの発生場所、内容がわかる
    image.png

  • 数値を入力しなおすとエラーがクリアされる
    image.png

4. プログラムを作成する

4.1. Windowsフォーム

  • 以下のコンポーネントを配置する
コンポーネント NAME 内容
Label Label1 ラベル
TextBox AgeTextBox テキストボックス
Button CheckButton ボタン

4.2. コードビハインド

Form1.cs
using System.Text.RegularExpressions;

namespace ErrorProviderSample
{
    public partial class Form1 : Form
    {

        // ErrorProviderのインスタンスを生成
        ErrorProvider errorProvider = new ErrorProvider();

        // 正規表現を生成
        Regex notIntRegex = new Regex(@"[^0-9]"); //数字以外にマッチする

        public Form1()
        {
            InitializeComponent();
            // アイコンを点滅なしに設定する
            errorProvider.BlinkStyle = ErrorBlinkStyle.NeverBlink;
        }


        /// <summary>
        /// Ageテキストボックスを変更した時
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AgeTextBox_TextChanged(object sender, EventArgs e)
        {
            int i = AgeTextBox.SelectionStart;
            AgeTextBox.Text = notIntRegex.Replace(AgeTextBox.Text, "");
            AgeTextBox.SelectionStart = i;
        }

        /// <summary>
        /// Ageテキストボックスの検証コードを呼び出す
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AgeTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!string.IsNullOrEmpty(AgeTextBox.Text)) {
                // 正常に整数に変換できた場合はエラーをクリアする
                errorProvider.SetError(AgeTextBox, "");
                AgeTextBox.BackColor = Color.White;
            }
        }
        
        /// <summary>
        /// Checkボタンをクリックした時
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckButton_Click(object sender, EventArgs e)
        {
            // 必須入力チェック
            if (string.IsNullOrEmpty(AgeTextBox.Text))
            {
                // 例外が発生したのでエラーを表示する
                errorProvider.SetError(AgeTextBox, "Ageは入力必須です");
                AgeTextBox.BackColor = Color.LightPink;

                return;
            }

            MessageBox.Show("入力チェックOK");
        }
    }
}
  • ErrorProviderクラス(エラー表示)、Regexクラス(正規表現)を生成する
  • 起動時にErrorProviderクラスをアイコンを点滅なしに変更する(デフォルトは点滅)
  • TextChangedメソッドで数値以外の値が入力された場合、テキストボックスへ反映しないようにする
  • Validatingメソッドで必須入力がOKの場合、エラーをクリアする(前のメソッドがあるため、数値以外の値は入らないはず)
  • Checkボタンをクリックした時に必須入力チェックを行う

5. ソースコード

6. 参考文献

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?