angular6 響應式表單: 添加自定義驗證器-----及其使用實踐


思路:

1.單獨配置一個驗證器文件 

ng g d validata.directive.ts

D:\cmf\angular6\project1>ng g d ../directive/validataform
CREATE src/directive/validataform.directive.spec.ts (248 bytes)
CREATE src/directive/validataform.directive.ts (153 bytes)
UPDATE src/app/app.module.ts (1299 bytes)

目錄結構 跟src目錄同級 加../

 

首先就要在app.module.ts里注冊上這個指令

 

1)import:

import { ValidataformDirective } from '../directive/validataform.directive';

2)@NgModule  declarations

@NgModule({
  declarations: [
  .......
  ValidataDirective,
  ValidataformDirective
],

 

 

2.自定義驗證器添加

導入用到的模塊

import { Directive , Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';

 

1.建立驗證器文件創建自定義驗證函數

1)定義驗證函數

實例

這里定義到單獨的文件里

project1\src\directive\validataform.directive.ts

ng命令

ng -g directive  validataform

目錄如下

 

自定義驗證函數 validateUrl 

注意的一點就是 return返回值定義 這里實例就是返回 inValidUrl,前端根據這個返回值去顯示信息

export function validateUrl(control: AbstractControl) {
      if (control.value) {
      if (!control.value.startsWith('www') ) {
              return {
                  inValidUrl: true
                 };
                      }
        }
      return null;
}

 

 

2.導入函數並添加到響應式表單中

1)然后在需要展示的組件里 project1\src\app\addsite1\addsite1.component.ts 導入文件中的函數

import { ValidataformDirective, validateUrl, urlmatch } from '../../directive/validataform.directive';

2)新建的響應式表單函數里添加

formcreat() {
    return this.addsiteform1 = new FormGroup({
       name:   new FormControl('', [
          Validators.required,
          Validators.minLength(2),
       ]),
       address:   new FormControl('', [
          Validators.required,
          validateUrl

       ]),
       descrition:  new FormControl(''),
       tag:     new FormControl(''),
       linkclass:    new FormControl('', [
          Validators.required,
       ])
       });
    }

 

ngOnInit() {
    this.addsiteform1 = this.formcreat();
}

 

3.模板html里添加報錯提示信息

在模板內 project1\src\app\addsite1\addsite1.component.html

根據返回值去判斷 inValidUrl

 

<div class="form-group">
<div class="input-group">
<label for="address">鏈接地址:(*必填)</label>
<input id="address" type="text" required formControlName="address" class="form-control"/>
</div>
<div class="alert alert-danger" *ngIf="address.invalid && ( address.dirty || address.touched )">

<div *ngIf="address.errors.required">
鏈接地址必須填寫!
</div>
<div *ngIf="address.errors.inValidUrl">
url格式不正確!必須以http://開頭或者https://開頭
</div>

</div>
</div>

 

 

這里是判斷網址url格式 正則匹配

http:// 或者https:// 開頭

export function urlmatch(control: AbstractControl) {

const ruler = /^((ht|f)tps?):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?/;
const testurl = ruler.test(control.value);
return testurl ? null : { 'testurl' : { value: control.value } };
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM