angular - 如何使用setcustomvalidity函数

问题描述 投票:0回答:1

我尝试使用html setcustomvalidity方法设置我的商业验证,但表单不能阻止自定义有效性。如何在角度使用此功能?

形成:

export class AutoComponent {
  autoFiled: any;
  
  @ViewChild('autoForm') autoForm;
  @ViewChild('autoInput', { read: ElementRef}) autoInput: ElementRef;
  
  check() {
    if (autoField != '123') {
      this.autoInput.nativeElement.setCustomValidity('Not Equals 123');
      this.autoForm.submitted = true;
      return false;
    }
    
    return true;
  }
}
<form novalidate #autoForm="ngForm"
  [class.invalid]="!autoForm.submitted">
  <input #autoInput type="text" name="auto" [(ngModel)]="autoField"/>
</form>
html angular html5
1个回答
1
投票

要在模板驱动的表单中添加验证,您需要创建自定义指令

import { Directive } from '@angular/core';
import { NG_VALIDATORS, AbstractControl } from '@angular/forms';
@Directive({
  selector: '[appCustomVaidator]',
  providers:[{
    provide: NG_VALIDATORS,
    useValue: equalCheck,
    multi: true
  }],
  exportAs:'appCustomVaidator'
})
export class CustomVaidatorDirective {
  constructor() { }
}
function equalCheck(c:AbstractControl){
  if(!c.value) return null;
  return  c.value != 123 ? { notEqual: true} : null;   
}

参考:: https://angular.io/guide/form-validation

例如:https://stackblitz.com/edit/angular-template-drive-form-customvalidator

© www.soinside.com 2019 - 2024. All rights reserved.