这里使用的是模型驱动的表单

1、app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
...
imports: [ReactiveFormsModule, ...],
...
})
export class AppModule{
}

文件中加入了ReactiveFormsModule模块,它是使用模型驱动表单所必须的。

2、app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name: string
score: number;
formData: any; constructor() { } ngOnInit() {
this.formData = new FormGroup({
name: new FormControl(this.name, Validators.compose([
Validators.required,
])),
score: new FormControl(this.score, Validators.compose([
Validators.required,
this.scoreValueValidator
]))
});
} scoreValueValidator(control: FormControl): any {
if (control.value < 0 || control.value > 100) {
return { value: {info: '分数必须大于等于0,小于等于100'} };
}
} onsubmit(data: any) {
this.name= data.name;
this.score = data.score
} }

表单验证,可以使用内置的表单验证,也可以使用自定义验证方法。

(1)  内置表单验证。

Validators是angular内置的验证器模块,可以使用它实现强制字段、最小长度、最大长度和模式等,我这里设置了name和score是强制字段,当然,你可以加入Validators.minLength(6), Validators.maxLength(10),Validators.pattern("[^ @]*@[^ @]*")等等。

(2)  自定义表单验证。

scoreValueValidator是自定义的验证方法,用于验证分数是否大于等于0,小于等于100,传递的参数是当前需要验证的表单的FormControl,通过control.value可以拿到输入的分数值。

3、app.component.html

<div class="container">
<form [formGroup] = "formData" (ngSubmit) = "onsubmit(formData.value)">
<div class="form-group">
<label for="name">姓名</label>
<em>*</em>
<input type="text" class="form-control" formControlName="name" id="name">
<div [hidden]="formData.get('name').valid || formData.get('name').untouched" class="small">
<p [hidden]="!formData.hasError('required', 'threshold')">必填项</p>
</div>
</div>
<div class="form-group">
<label for="score">分数</label>
<em>*</em>
<input type="number" min="0" max="100" class="form-control" formControlName="score" id="score">
<div [hidden]="formData.get('score').valid || formData.get('score').untouched" class="small">
<p [hidden]="!formData.hasError('required', 'score')">必填项</p>
<p [hidden]="!formData.hasError('value', 'score')">{{formData.getError('value', 'score')?.info}}</p>
</div>
<button type="submit" [disabled]="!formData.valid" class="btn btn-sm btn-primary">提交</button>
</form>
</div>

页面中显示错误信息

对于提交按钮,我们已经在方括号中添加了disabled,它被赋予值 !formData.valid。因此,如果formData.valid无效,按钮将保持禁用状态,用户将无法提交它。

4、app.component.css

em {
color:red;
margin-left: 0.25em
}
.ng-touched:not(form),.ng-invalid:not(form) {
border: 1px solid #f00;
}
.ng-valid:not(form),.ng-untouched:not(form) {
border: 1px solid #ddd;
}
p{
color:#f00;
}

angular6 表单验证的更多相关文章

  1. jQuery学习之路(8)- 表单验证插件-Validation

    ▓▓▓▓▓▓ 大致介绍 jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证变得更简单,同时提供了大量的定制选项,满足应用程序各种需求.该插件捆绑了一套有用的验证方法,包括 ...

  2. 玩转spring boot——AOP与表单验证

    AOP在大多数的情况下的应用场景是:日志和验证.至于AOP的理论知识我就不做赘述.而AOP的通知类型有好几种,今天的例子我只选一个有代表意义的“环绕通知”来演示. 一.AOP入门 修改“pom.xml ...

  3. form表单验证-Javascript

    Form表单验证: js基础考试内容,form表单验证,正则表达式,blur事件,自动获取数组,以及css布局样式,动态清除等.完整代码如下: <!DOCTYPE html PUBLIC &qu ...

  4. ASP.NET MVC5+EF6+EasyUI 后台管理系统(33)-MVC 表单验证

    系列目录 注:本节阅读需要有MVC 自定义验证的基础,否则比较吃力 一直以来表单的验证都是不可或缺的,微软的东西还是做得比较人性化的,从webform到MVC,都做到了双向验证 单单的用js实现的前端 ...

  5. 实现跨浏览器html5表单验证

    div:nth-of-type(odd){ float: left; clear: left; } .origin-effect > div:nth-of-type(even){ float: ...

  6. jQuery Validate 表单验证 — 用户注册简单应用

    相信很多coder在表单验证这块都是自己写验证规则的,今天我们用jQuery Validate这款前端验证利器来写一个简单的应用. 可以先把我写的这个小demo运行试下,先睹为快.猛戳链接--> ...

  7. jquery validate表单验证插件-推荐

    1 表单验证的准备工作 在开启长篇大论之前,首先将表单验证的效果展示给大家.     1.点击表单项,显示帮助提示 2.鼠标离开表单项时,开始校验元素  3.鼠标离开后的正确.错误提示及鼠标移入时的帮 ...

  8. 表单验证插件之jquery.validate.js

    提到表单验证的插件,第一个想到的就是jquery.validate.js,所以小生想在这里稍微详细地说一下这款插件的具体使用方法,便于理解,我直接附上整段demo的代码(没怎么调样式,主要是看js): ...

  9. 走进AngularJs 表单及表单验证

    年底了越来越懒散,AngularJs的学习落了一段时间,博客最近也没更新.惭愧~前段时间有试了一下用yeoman构建Angular项目,感觉学的差不多了想做个项目练练手,谁知遇到了一系列问题.yeom ...

随机推荐

  1. SpringCloud学习笔记(七、SpringCloud Netflix Zuul)

    目录: springcloud整合eureka.config.zuul zuul源码分析 springcloud整合eureka.config.zuul: 1.架构图 2.GitHub:https:/ ...

  2. 一,java框架学习

    一,java框架学习 Hibernate概述Hibernate是一个开放源代码的ORM(对象关系映射)框架,对jdbc进行了轻量级的封装,是的java开发人员可以使用面向对象编程思想操作数据库,简化操 ...

  3. python3.5.3rc1学习四:类

    class calculator: def add(x,y): return x + y print(added) def sub(x,y): return x - y print(sub) def ...

  4. 【ECNU620】数学题(结论题)

    点此看题面 大致题意: 求\((n-1)!\ mod\ n\)的值. 大力猜结论 首先,看到样例,我们可以猜测: 当\(n\)为质数时,答案为\(n-1\). 当\(n\)为合数时,答案为\(0\). ...

  5. hw笔试题-02

    #include<stdio.h> #include<string.h> typedef struct { char *mem; char len; }m_table_t; i ...

  6. windows端口转发工具(LCX)

    端口转发(Port forwarding),有时被叫做隧道,是安全壳(SSH) 为网络安全通信使用的一种方法.端口转发是转发一个网络端口从一个网络节点到另一个网络节点的行为,其使一个外部用户从外部经过 ...

  7. 在线web软件

    编程 Compiler Explorer SharpLab 着色器 shadertoy 腾讯文档 word  excel  ppt ... 思维导图 MindMaster ProcessOn 流程图. ...

  8. PMP图表(必背)

  9. Windows Terminal (Preview)治好了cmd,powershell的癌症

    前言 话说n年前,我想开发一款powershell麻将游戏,但是发现命令行下无法显示麻将牌这种特殊符号. 经过研究发现,这是4字节的utf16le字符串.而powershell依赖的渲染引擎,只能渲染 ...

  10. C# 5.0 新特性之异步方法(AM)

    Ø  前言 C# Asynchronous Programming(异步编程)有几种实现方式,其中 Asynchronous Method(异步方法)就是其中的一种.异步方法是 C#5.0 才有的新特 ...