Tạo Custom Validation trong Angular

Giới thiệu nội dung bài viết

Chào các bạn, hôm nay anh sẽ hướng dẫn mọi người cách Custom Validation là như thế nào?

1.Custom Validation là gì

Angular hỗ trợ một số validator như required, minlength, maxlength, pattern và email như ta đã xem ở bài trước. Ngoài những validator có sẵn của Angular ta hoàn toàn có thể tự tạo một validator cho dự án của mình.

2.Sử dụng Validator như thế nào

Giả sử ta có form trong file template html như sau.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<h1>Custom Validator in Angular</h1>
 
<h2>Reactive Form</h2>
 
<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
 
  <div>
    <label for="numVal">Number :</label>
    <input type="text" id="numVal" name="numVal" formControlName="numVal">
  </div>
 
  <p>Is Form Valid :  </p>
 
  <p>
    <button type="submit" [disabled]="!myForm.valid">Submit</button>
  </p>
 
</form>

Như các em thấy ta có 1 field trong form là numVal. Chúng ta muốn giá trị trong numVal phải lớn hơn 10.

Bây giờ ta sẽ định nghĩa một Validator riêng cho việc kiểm tra giá trị lớn hơn 10. Ta tạo một file gte.validator.js như sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { AbstractControl, ValidationErrors } from '@angular/forms'
 
export function gte(control: AbstractControl): ValidationErrors | null {
 
    const v=+control.value;
 
    if (isNaN(v)) {
      return { 'gte': true, 'requiredValue': 10 }
    }      
 
    if (v <= 10) {
      return { 'gte': true, 'requiredValue': 10 }
    } 
 
    return null
 
}

Đầu tiên chúng ta import thư viện AbstractControl và Validation Error từ Angular Form.

1
import { AbstractControl, ValidationErrors } from '@angular/forms'

ValidatorError chứa cặp key và value. Key là tên của rule chúng ta muốn sử dụng và value có thể làm bất cứ cái gì.

Trong ví dụ sau chúng ta kiểm tra giá trị của control có phải là số hay không. Để kiểm tra số ta dùng hàm isNaN. Đồng thời kiểm tra giá trị nhỏ hơn hay bằng 10. Nếu cả 2 điều kiện là đúng thì trả về null.

1
2
3
4
5
6
7
8
9
10
11
const v=+control.value;
 
    if (isNaN(v)) {
      return { 'gte': true, 'requiredValue': 10 }
    }      
 
    if (v <= 10) {
      return { 'gte': true, 'requiredValue': 10 }
    } 
 
    return null

Nếu validator bị sai thì trả về Validator Error.

1
return { 'gte': true, 'requiredValue': 10 }

Để sử dụng Custom validator chúng ta import vào component class.

1
import { gte } from './gte.validator';

Thêm validator vào form như sau.

1
2
3
 myForm = new FormGroup({
    numVal: new FormControl('', [gte]),
  })

3. Code hoàn chỉnh cho component class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { Component } from '@angular/core';
import { FormGroup, FormControl, AbstractControl, ValidationErrors } from '@angular/forms'
import { gte } from './gte.validator';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
  constructor() {
  }
 
  myForm = new FormGroup({
    numVal: new FormControl('', [gte]),
  })
 
  get numVal() {
    return this.myForm.get('numVal');
  }
 
  onSubmit() {
    console.log(this.myForm.value);
  }
}

4. Code hoàn chỉnh cho template html

1
2
3
4
5
6
7
8
9
10
 <div>
    <label for="numVal">Number :</label>
    <input type="text" id="numVal" name="numVal" formControlName="numVal">
    <div *ngIf="!numVal.valid && (numVal.dirty ||numVal.touched)">
      <div *ngIf="numVal.errors.gte">
        The number should be greater than 
      </div>
    </div>
 
  </div>

6. Demo Video

6. Source code

Sourcecode


Mọi người hãy Subscribe kênh youtube dưới đây nhé để cập nhật các video mới nhất về kỹ thuật và kỹ năng mềm

Các khoá học lập trình MIỄN PHÍ tại đây


Comments