โอเค 😎 เรามาเรียน RuleFor
ของ FluentValidation แบบเข้าใจง่าย พร้อมตัวอย่างจริง ๆ
1️⃣ RuleFor
คืออะไร?
-
RuleFor
เป็น Method ของ FluentValidation -
ใช้สำหรับ กำหนดกฎ (Validation Rules) ให้กับ Property ของ Object
-
อ่านง่าย เหมือนประโยคภาษาอังกฤษ เช่น “Name ต้องไม่ว่าง” หรือ “Age ต้องระหว่าง 18-60”
2️⃣ ติดตั้ง FluentValidation
Install-Package FluentValidation
3️⃣ ตัวอย่างใช้งาน
Step 1: สร้าง Model
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
Step 2: สร้าง Validator
using FluentValidation;
public class UserValidator : AbstractValidator<User>
{
public UserValidator()
{
// Name ต้องไม่ว่าง
RuleFor(user => user.Name)
.NotEmpty()
.WithMessage("Name is required");
// Age ต้องอยู่ระหว่าง 18-60
RuleFor(user => user.Age)
.InclusiveBetween(18, 60)
.WithMessage("Age must be between 18 and 60");
// Email ต้องเป็น format email
RuleFor(user => user.Email)
.NotEmpty()
.EmailAddress()
.WithMessage("Invalid email address");
}
}
4️⃣ การใช้งาน Validator
var user = new User { Name = "", Age = 17, Email = "invalid-email" };
var validator = new UserValidator();
var result = validator.Validate(user);
if(!result.IsValid)
{
foreach(var error in result.Errors)
{
Console.WriteLine(error.ErrorMessage);
}
}
Output:
Name is required
Age must be between 18 and 60
Invalid email address
5️⃣ RuleFor แบบ Advance
-
เงื่อนไขแบบ Custom
RuleFor(x => x.Name)
.Must(name => name.StartsWith("J"))
.WithMessage("Name must start with J");
-
เงื่อนไขแบบ dependent property
RuleFor(x => x.Age)
.GreaterThan(18)
.When(x => x.Name == "Jen")
.WithMessage("Jen must be older than 18");
-
ใช้ Regular Expression
RuleFor(x => x.Email)
.Matches(@"^[^@\s]+@[^@\s]+\.[^@\s]+$")
.WithMessage("Email is not valid");
💡 สรุปง่าย ๆ:
-
RuleFor(x => x.Property)
→ กำหนดกฎให้ Property นั้น -
ต่อด้วย Validation Methods เช่น
NotEmpty()
,Length()
,InclusiveBetween()
,EmailAddress()
,Matches()
-
ต่อด้วย
.WithMessage("ข้อความ")
→ กำหนดข้อความเมื่อ Validation ผิด
ถ้าคุณอยาก ฉันสามารถทำ ตาราง Cheat Sheet ของ RuleFor ทุก Method ที่ใช้บ่อย พร้อมตัวอย่างสั้น ๆ ให้คุณเอาไปใช้งานจริง ๆ เลย
คุณอยากให้ทำไหม?