C#에서는 커스텀 어트리뷰트를 활용해 간단한 유효성 검증 시스템을 만들 수 있습니다. 이번 글에서는 기본적인 Attribute 정의부터 적용, 그리고 검증 로직 구현까지 실용적인 예제를 다룹니다.
1. 커스텀 Attribute 정의하기
유효성 검사 규칙을 명시하는 어트리뷰트를 만들어 봅니다. 예를 들어, 필수값 검사용 RequiredAttribute를 정의합니다.
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class RequiredAttribute : Attribute
{
public string ErrorMessage { get; set; } = "필수 입력 항목입니다.";
}
2. 검증 대상 클래스에 Attribute 적용하기
속성에 커스텀 어트리뷰트를 붙여 유효성 조건을 지정합니다.
public class User
{
[Required(ErrorMessage = "이름은 반드시 입력해야 합니다.")]
public string Name { get; set; }
public int Age { get; set; }
}
3. 유효성 검사 로직 구현하기
리플렉션을 활용해 속성의 Attribute를 확인하고, 조건을 검사합니다.
public static class Validator
{
public static List<string> Validate(object obj)
{
var errors = new List<string>();
var type = obj.GetType();
foreach (var prop in type.GetProperties())
{
var requiredAttr = prop.GetCustomAttribute<RequiredAttribute>();
if (requiredAttr != null)
{
var value = prop.GetValue(obj);
if (value == null || (value is string str && string.IsNullOrWhiteSpace(str)))
{
errors.Add(requiredAttr.ErrorMessage);
}
}
}
return errors;
}
}
4. 사용 예
간단하게 객체를 만들어 검증 결과를 확인해 봅니다.
var user = new User { Name = "", Age = 25 };
var errors = Validator.Validate(user);
foreach (var error in errors)
{
Console.WriteLine(error);
}
이처럼 Attribute 기반 유효성 검증 시스템을 구현하면 재사용성과 유지보수가 편리한 코드 구조를 만들 수 있습니다.
'C#' 카테고리의 다른 글
| C# 구조체를 읽기 전용(ReadOnly Struct)으로 설계하기 (0) | 2026.05.20 |
|---|---|
| C# 동시 컬렉션(Concurrent Collections) 활용하기 (0) | 2026.05.19 |
| C# 전처리 지시문(Preprocessor Directives) 심층 탐구 (0) | 2026.05.18 |
| C# 메모리 매핑 파일(Memory-Mapped File) 사용하기 (0) | 2026.05.18 |
| C# TimeSpan과 Stopwatch로 성능 측정 및 시간 연산 (0) | 2026.05.16 |