ionic2 + cordova 应用-表单
程序员文章站
2022-05-31 08:22:05
...
4.1 静态页面login.html(欢迎加入Q群一起学习讨论657185219)
<ion-content padding> <form [formGroup]="loginForm" > <ion-item> <ion-label>Username</ion-label> <ion-input type="text" formControlName="LoginID"></ion-input> </ion-item> <!-- 有问题的提示语 --> <p *ngIf="!loginForm.controls.LoginID.valid && loginForm.controls.LoginID.touched" color="danger">LoginID must is email.</p> <!-- <p *ngIf="loginForm.controls.LoginID.valid && loginForm.controls.LoginID.touched" secondary> LoginID is good</p>--> <ion-item> <ion-label>Password</ion-label> <ion-input type="password" formControlName="LoginPwd"></ion-input> </ion-item> <ion-item> <button ion-button (click)="login(loginForm.value, $event)" [disabled]="!loginForm.valid">登录</button> <button ion-button (click)="signup()">注册</button> </ion-item> </form> </ion-content>主要使用了[formGroup],loginForm.controls 俩个属性
4.1.1 校验的属性说明(可参考model.d.ts所有属性都在)
/** * A control is marked `touched` once the user has triggered * a `blur` event on it. * 鼠标点击过blur后触发touched */ readonly touched: boolean; // 其他慢慢看吧
4.2 login.ts
4.2.1 引入form,具体的看对象form源码文件
import { FormBuilder, Validators } from '@angular/forms';
其中引入FormBuilder,Validators为了在ts中加上校验
4.2.2 加入自定义校验
loginForm = this.formBuilder.group({ 'LoginID': ['admin@163.com2', [Validators.required, Validators.minLength(4), emailValidator]],// 第一个参数是默认值 'LoginPwd': ['123456', [Validators.required, Validators.minLength(4)]] });
下面自定义方法在validator.ts
import {FormBuilder,FormControl,Validators,AbstractControl } from '@angular/forms'; export function emailValidator(control: FormControl): { [s: string]: boolean } { if (!control.value.match(/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/)) { return { invalidEmail: true }; } }
4.2.3 在login方法里加入自己的业务逻辑
login(user, _event) { //自己的业务逻辑 let toast = this.toastCtrl.create({ message: '正在登陆', duration: 3000, position: 'middle', showCloseButton: true, closeButtonText: '关闭' }); toast.present(); }