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

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. 11.Java基础_IDEA常用快捷键

    /* 内容辅助键: psvm 回车 : 快速生成main方法: sout 回车 : 快速生成输出代码 Ctrl+Alt+Space : 内容提示,代码补全 快捷键: 注释: 单行: 选中代码, Ctr ...

  2. 【转】Redis常见面试题

    介绍:Redis 是一个开源的使用 ANSI C 语言编写.遵守 BSD 协议.支持网络.可基于内存亦可持久化的日志型.Key-Value 数据库,并提供多种语言的 API的非关系型数据库. 传统数据 ...

  3. 【Eureka篇三】Eureka服务注册(2)

    注:修改[Rest微服务案例(二)]中的子模块microservicecloud-provider-dept-8001. 一.项目改造 1. 修改pom.xml 添加eureka client的依赖 ...

  4. CF1225C p-binary

    CF1225C p-binary 洛谷评测传送门 题目描述 Vasya will fancy any number as long as it is an integer power of two. ...

  5. 洛谷 P5594 【XR-4】模拟赛

    洛谷 P5594 [XR-4]模拟赛 洛谷传送门 题目描述 X 校正在进行 CSP 前的校内集训. 一共有 nn 名 OIer 参与这次集训,教练为他们精心准备了 mm 套模拟赛题. 然而,每名 OI ...

  6. 历届试题 青蛙跳杯子-(bfs)

    题目:http://lx.lanqiao.cn/problem.page?gpid=T448 题意:有两个字符串例如*WWBB和WWBB*,*每次能往左或右跳1-3步,与原位置的字符交换,问最少步数跳 ...

  7. C读取json格式字符串

    python调用C库时参数太多,约定传json格式字符串,C解析 #include<stdio.h> #include<string.h> #include<stdlib ...

  8. vue+Element 表格中的树形数据

    template部分   只在树形的结构中显示编辑与删除按钮 这里我只是简单的做了一个 v-if 判断在操作列中 ,判断是否存在级别这个字段 <div> <el-table :dat ...

  9. 1+x 证书 Web 前端开发 MySQL 知识点梳理

    官方QQ群 1+x 证书 Web 前端开发 MySQL 知识点梳理 http://blog.zh66.club/index.php/archives/199/

  10. ideal 切换git和svn

    原文地址:https://blog.csdn.net/lixld/article/details/98851427 intellij ideal gi和svn切换: 之前项目是svn的,新的项目用了g ...