ng2-validation/angular2表单验证模块使用方法

效果图
ng2-validation/angular2表单验证模块使用方法_第1张图片

官方参考文档:https://github.com/yuyang0410...

注意:

  1. 验证是在组件重定义的变量,然后通过界面中的 #username="ngModel"这个样式来验证的,和[(ngModel)]="username"无关

  2. 提交按钮可以设置如果验证不通过,就处于只读状态

1、安装模块

npm install ng2-validation --save

2、配置app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {CustomFormsModule} from "ng2-validation";
...
imports: [
    FormsModule,
    CustomFormsModule,
    ReactiveFormsModule
  ],
...

3、配置组件,官方文档有详细的配置方法。

import {Component} from '@angular/core';
// 1. 引入forms中的组件
import {FormGroup, FormControl} from '@angular/forms';
// 2. 引入ng2-validation中的组件
import {CustomValidators} from 'ng2-validation';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // 3. 定义表单组
  form:FormGroup;

  constructor() {
    // 4. 初始化表达组里面的内容
    this.form = new FormGroup({
      // 定义form.field 是一个区间
      field: new FormControl('', CustomValidators.range([5, 9])),
      // 定义form.num 是数字类型
      num: new FormControl('', CustomValidators.number)
    });
  }
}

4、配置模板,使用




输入字符长度在5-9之间

只能输入数字

5、添加多个条件

1. 组件配置
constructor() {
    // 初始化表达组里面的内容
    this.form = new FormGroup({
      username: new FormControl('', CustomValidators.range([5, 9])),
      max: new FormControl('', CustomValidators.max(100)),
      min: new FormControl('', CustomValidators.min(0)),
      num: new FormControl('', CustomValidators.number),
      phone: new FormControl('', CustomValidators.phone('zh-CN'))
    });
  }
2. 模块配置

只能输入0-100数字

6、示例代码

输入字符长度在5-9之间

手机号码格式不正确

邮箱地址不正确

网络地址格式不正确

只能输入数字

职位不详细

字少两个字,最多50个字

import {Component} from "@angular/core";
// 1. 引入forms中的组件
import {FormGroup, FormControl, Validators} from '@angular/forms';
// 2. 引入ng2-validation中的组件
import {CustomValidators} from 'ng2-validation';
@Component({
  selector: "oa-add-friends",
  templateUrl: "../templates/add_friends.component.html"
})
export class AddFriendsComponent {
  // 3. 定义表单组
  form:FormGroup;

  constructor() {
    // 4. 初始化表达组里面的内容
    this.form = new FormGroup({
      // 定义form.field 是一个区间
      username: new FormControl('', CustomValidators.range([6, 20])),
      // 定义form.num 是数字类型
      age: new FormControl('', CustomValidators.number),
      sex: new FormControl('', Validators.required),
      position: new FormControl('', CustomValidators.range([2, 20])),
      habby: new FormControl('', CustomValidators.range([2, 50])),
      phone: new FormControl('', CustomValidators.phone("zh-CN")),
      email: new FormControl('', CustomValidators.email),
      url: new FormControl('', CustomValidators.url)
    });
  }
}

#num=“ngModel” #max=“ngModel” #min=“ngModel”表示是在组件中配置的项目,然后在*ngIf中添加判断提醒。

你可能感兴趣的:(form,validation,angular2)