Trung BìnhAngular iconAngular

Custom validator trong Reactive Forms viết như thế nào?

Validator là function nhận AbstractControl và trả về ValidationErrors | null.

Ví dụ cross-field validator:

typescript
function passwordsMatch(group: AbstractControl): ValidationErrors | null {
  const password = group.get("password")?.value
  const confirm = group.get("confirm")?.value

  return password === confirm ? null : { passwordMismatch: true }
}

Async validator phù hợp check server như username đã tồn tại; cần debounce/cancel để không bắn request quá nhiều.

Xem toàn bộ Angular cùng filter theo level & chủ đề con.

Mở danh sách Angular