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

相关文章
相关标签/搜索