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

思路:html

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

ng g d validata.directive.tsapp

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目錄同級 加../ui

 

首先就要在app.module.ts裏註冊上這個指令this

 

1)import:url

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

2)@NgModule  declarationscomponent

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

 

 

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 } };
}

相關文章
相關標籤/搜索