angular 4自定义验证器无法正常工作

时间:2017-10-19 16:19:50

标签: angular typescript

我正在处理angular 4并在component.ts文件中为cgpa验证创建了一个自定义验证器(如果cgpa小于或大于4.0),但它没有触发,但预定义的Validators.required是工作正常。

Cgpa验证员:

 function ValidCgpa(cgpa: FormControl): {[s: string]: boolean}  {
  let num = Number(cgpa);

  if(num < 2.0 || num > 4.0)  {
    return {invalidCgpa: true};
  }
 }

自定义Cgpa验证器调用

this.educationalDetailsForm = new FormGroup({
  cgpa: new FormControl('', Validators.compose([Validators.required, ValidCgpa]))
});

HTML代码

<input type="text" formControlName="cgpa" placeholder="CGPA">

<div *ngIf="educationalDetailsForm.hasError('ValidCgpa','cgpa') && educationalDetailsForm.get('cgpa').touched">
   CGPA must be greater than 2.0 and less than 4.0
</div>

3 个答案:

答案 0 :(得分:0)

我认为你实现验证器的方式是错误的,尝试这样的事情(未经测试):

export function ValidCgpa(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} => {
    const num = Number(cgpa.value);
    if(num < 2.0 || num > 4.0)  {
       return {invalidCgpa: true};
    }
  };
}

答案 1 :(得分:0)

使用这种方式

自定义验证器

import { AbstractControl } from '@angular/forms';

export function ValidateGpa(control: AbstractControl) {
  const num = Number(control.value);
  if (num < 0 || num > 4.0) {
    return { invalidGpa: true };
  }
  return null;
}

以html

<h1>Type here and Check</h1>
<input type="text"  [formControl]="gpa">
<br>
<div *ngIf="gpa.errors?.invalidGpa">Invalid GPA value</div>

在打字稿文件中

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ValidateGpa } from './validators/valid-gpa.validator';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {

  gpa = new FormControl('', [Validators.required, ValidateGpa]);
}

尝试这个example in stackblitz

答案 2 :(得分:-1)

我更喜欢对HTML直接进行验证,如下所示:

<input type="number" required name="cgpa" [(ngModel)]="cgpaValue" #cgpa="ngModel">

<div *ngIf="cgpa.touched && (!cpga.valid || cpga.value < 2 || cpga.value > 4 )">
    CGPA must be greater than 2.0 and less than 4.0 
</div>