본문 바로가기
Study/C#

C# Windows Forms 강의 22편: 사용자 입력 검증(Input Validation)

by wawManager 2025. 2. 25.
728x90

1. 강의 개요

이번 강의에서는 Windows Forms 애플리케이션에서 **사용자 입력 검증(Input Validation)**을 구현하는 방법을 학습합니다.
입력 검증은 사용자가 잘못된 데이터를 입력하거나 애플리케이션을 예상치 못한 방식으로 사용하는 것을 방지하여 안정성과 보안성을 높이는 데 필수적입니다.


2. 학습 목표

  1. 사용자 입력 값을 검증하여 유효한 데이터만 처리.
  2. 입력 값이 올바르지 않을 경우 오류 메시지 표시.
  3. 정규 표현식(Regex)을 사용하여 입력 값의 형식을 검사.

3. 입력 검증이란?

**입력 검증(Input Validation)**은 사용자가 입력한 데이터가 유효한지 검사하고, 조건에 맞지 않을 경우 적절히 처리하는 과정을 의미합니다.

  • 형식 검증: 숫자, 이메일, 날짜 등 데이터 형식을 확인.
  • 범위 검증: 값이 지정된 범위 내에 있는지 확인.
  • 공백 또는 빈 값 체크: 필수 입력란이 비어 있지 않은지 확인.

4. 실습: 사용자 입력 검증 구현

요구사항

  1. 사용자 이름(문자만 입력), 나이(숫자만 입력), 이메일(유효한 형식) 입력란을 제공.
  2. 버튼 클릭 시 입력 값을 검증.
  3. 잘못된 입력 값은 오류 메시지를 통해 사용자에게 알림.

폼 구성

컨트롤 타입 이름 텍스트 위치 크기

Label lblName "이름:" (20, 20) (50 x 20)
TextBox txtName (없음) (100, 20) (150 x 20)
Label lblAge "나이:" (20, 60) (50 x 20)
TextBox txtAge (없음) (100, 60) (150 x 20)
Label lblEmail "이메일:" (20, 100) (50 x 20)
TextBox txtEmail (없음) (100, 100) (150 x 20)
Button btnValidate "검증하기" (20, 140) (100 x 30)

코드 작성

Form1.cs

using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnValidate_Click(object sender, EventArgs e)
        {
            // 이름 검증
            if (string.IsNullOrWhiteSpace(txtName.Text) || !IsAlphabetic(txtName.Text))
            {
                MessageBox.Show("이름은 필수 입력 항목이며, 문자만 입력할 수 있습니다.", "입력 오류");
                return;
            }

            // 나이 검증
            if (string.IsNullOrWhiteSpace(txtAge.Text) || !int.TryParse(txtAge.Text, out int age) || age <= 0)
            {
                MessageBox.Show("나이는 필수 입력 항목이며, 양의 정수만 입력할 수 있습니다.", "입력 오류");
                return;
            }

            // 이메일 검증
            if (string.IsNullOrWhiteSpace(txtEmail.Text) || !IsValidEmail(txtEmail.Text))
            {
                MessageBox.Show("유효한 이메일 주소를 입력하세요.", "입력 오류");
                return;
            }

            // 검증 성공 메시지
            MessageBox.Show("모든 입력 값이 유효합니다!", "검증 완료");
        }

        // 알파벳만 허용하는 검증 메서드
        private bool IsAlphabetic(string input)
        {
            return Regex.IsMatch(input, @"^[a-zA-Z가-힣\s]+$");
        }

        // 이메일 형식 검증 메서드
        private bool IsValidEmail(string email)
        {
            return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
        }
    }
}

Form1.Designer.cs

namespace WindowsFormsApp1
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;
        private Label lblName;
        private TextBox txtName;
        private Label lblAge;
        private TextBox txtAge;
        private Label lblEmail;
        private TextBox txtEmail;
        private Button btnValidate;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.lblName = new Label();
            this.txtName = new TextBox();
            this.lblAge = new Label();
            this.txtAge = new TextBox();
            this.lblEmail = new Label();
            this.txtEmail = new TextBox();
            this.btnValidate = new Button();
            this.SuspendLayout();

            // lblName
            this.lblName.AutoSize = true;
            this.lblName.Location = new System.Drawing.Point(20, 20);
            this.lblName.Name = "lblName";
            this.lblName.Size = new System.Drawing.Size(50, 20);
            this.lblName.TabIndex = 0;
            this.lblName.Text = "이름:";

            // txtName
            this.txtName.Location = new System.Drawing.Point(100, 20);
            this.txtName.Name = "txtName";
            this.txtName.Size = new System.Drawing.Size(150, 27);
            this.txtName.TabIndex = 1;

            // lblAge
            this.lblAge.AutoSize = true;
            this.lblAge.Location = new System.Drawing.Point(20, 60);
            this.lblAge.Name = "lblAge";
            this.lblAge.Size = new System.Drawing.Size(50, 20);
            this.lblAge.TabIndex = 2;
            this.lblAge.Text = "나이:";

            // txtAge
            this.txtAge.Location = new System.Drawing.Point(100, 60);
            this.txtAge.Name = "txtAge";
            this.txtAge.Size = new System.Drawing.Size(150, 27);
            this.txtAge.TabIndex = 3;

            // lblEmail
            this.lblEmail.AutoSize = true;
            this.lblEmail.Location = new System.Drawing.Point(20, 100);
            this.lblEmail.Name = "lblEmail";
            this.lblEmail.Size = new System.Drawing.Size(50, 20);
            this.lblEmail.TabIndex = 4;
            this.lblEmail.Text = "이메일:";

            // txtEmail
            this.txtEmail.Location = new System.Drawing.Point(100, 100);
            this.txtEmail.Name = "txtEmail";
            this.txtEmail.Size = new System.Drawing.Size(150, 27);
            this.txtEmail.TabIndex = 5;

            // btnValidate
            this.btnValidate.Location = new System.Drawing.Point(20, 140);
            this.btnValidate.Name = "btnValidate";
            this.btnValidate.Size = new System.Drawing.Size(100, 30);
            this.btnValidate.TabIndex = 6;
            this.btnValidate.Text = "검증하기";
            this.btnValidate.UseVisualStyleBackColor = true;
            this.btnValidate.Click += new System.EventHandler(this.BtnValidate_Click);

            // Form1
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(300, 200);
            this.Controls.Add(this.btnValidate);
            this.Controls.Add(this.txtEmail);
            this.Controls.Add(this.lblEmail);
            this.Controls.Add(this.txtAge);
            this.Controls.Add(this.lblAge);
            this.Controls.Add(this.txtName);
            this.Controls.Add(this.lblName);
            this.Name = "Form1";
            this.Text = "입력 검증 예제";
            this.ResumeLayout(false);
            this.PerformLayout();
        }
    }
}

6. 실행 결과

  1. 올바른 입력
    • 이름: "홍길동"
    • 나이: "25"
    • 이메일: "test@example.com"
    • → "모든 입력 값이 유효합니다!" 메시지 표시.
  2. 잘못된 입력
    • 이름에 숫자 포함: "홍길동123" → 오류 메시지 표시.
    • 나이에 음수 또는 문자 입력: "-5" 또는 "abc" → 오류 메시지 표시.
    • 이메일 형식이 잘못됨: "test@com" → 오류 메시지 표시.

7. 주요 개념 요약

  1. 공백 및 빈 값 체크: string.IsNullOrWhiteSpace()로 필수 입력값 확인.
  2. 정규 표현식(Regex): 입력 값의 형식을 간단히 검증.
  3. 유효성 검사 프로세스: 모든 검증이 통과된 경우에만 처리 진행.

 

728x90