gpt4 book ai didi

angular - 在用户填写表单 Angular 2 时检查表单验证

转载 作者:太空狗 更新时间:2023-10-29 17:59:30 28 4
gpt4 key购买 nike

我创建了一个带有验证检查的表单,

import { FormGroup, Validators, FormControl } from "@angular/forms";

目前我有提交按钮 [disabled] 直到表单被正确填写。我向用户显示表单是否有效的唯一方法是在表单字段无效时在输入中显示红色。

enter image description here

我想向用户显示一条错误消息,告诉他们哪里出了问题。

Angular2 中是否内置了一些东西来显示错误消息或为什么输入字段无效?或者我是否需要为每个表单字段构建自定义错误消息?如果是这样,我将如何检查每个输入字段,比方说当有人离开各自字段的焦点时。因此,如果他们离开输入字段并且它无效,那么我可以显示一条消息告诉他们它无效以及为什么?

我有一种显示消息的方法,我只需要想出一种获取错误消息的方法。换句话说,从表单中生成有关其无效原因的文本。

示例

Please provide a valid mobile number

代码

正则表达式

  ngOnInit() {
this.personalForm = new FormGroup({
email : new FormControl(this.auth.user.email,Validators.required ),
first_name: new FormControl(null,[
Validators.required,
Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
]),
middle_name: new FormControl(null,[
Validators.required,
Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
]),

last_name: new FormControl(null,[
Validators.required,
Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
]),

dob : new FormControl (null, [
Validators.required,
Validators.pattern("[1][9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]|[2][0][0-9][0-9]-[0-9][0-9]-[0-9][0-9]")
]),
mobile_phone: new FormControl(null, [
Validators.required,
Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
]),
home_phone: new FormControl(null, [
Validators.required,
Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
]),

business_phone: new FormControl(null, [
Validators.required,
Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
]),
fax_number: new FormControl(null, [
Validators.required,
Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
]),
ssn: new FormControl(null, [
Validators.required,
Validators.pattern("[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]|[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
])
});
}

有效的 bool 值/处理表单数据

save(model: Personal, isValid: boolean) {
if (!isValid) {
console.log('Personal Form is not valid');
console.log(model, isValid);
} else {
console.log('Personal Form is valid');
console.log(model, isValid);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post('http://localhost:4200/api/updateProfile',
model,
{headers: headers})
.map((res: Response) => res.json())
.subscribe((res) => {
//do something with the response here
console.log(res);
});
}
}

表单

<form [formGroup]="personalForm" novalidate (ngSubmit)="save(personalForm.value, personalForm.valid)">
<div class="row">
<div class="col-sm-12 col-md-12 col-lg-12">
<div class="card card-inverse card-success">
<div class="card-header">
<strong>Personal Information</strong>
</div>
<div class="card-block">
<div class="row">
<div class="form-group col-sm-12 col-md-12">
<label for="email">Email</label>
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope"></i>
</span>
<input type="text" class="form-control" id="email" formControlName="email" placeholder="{{personal.email}}"readonly>
</div>
<div class="alert alert-danger" *ngIf="!personalForm.controls.email.valid && submitted ">
*Email is required.
</div>
</div>
</div>

最佳答案

总结

要访问 FormGroup input 字段,您可以使用 syntax 访问您创建的 controls

this.FormGroupName.get('ControlName').status

这将返回 VALIDINVALID

在我的例子中,这是如何完成的,

示例

导入正确的包,

import {FormGroup, Validators, FormControl } from "@angular/forms";
import {INVALID, VALID} from "@angular/forms/src/model";

创建FormGroup,

personalForm: FormGroup;

创建FormControl,

 ngOnInit() {
this.personalForm = new FormGroup({
first_name: new FormControl(null,[
Validators.required,
Validators.pattern("^[a-zA-Zñáéíóúü']{1,30}$")
]),
});
}

FormControlName 添加到 form 和要检查 error 时调用的 function .

<input (blur)="firstNameValidate('*First Name Required', 'Use 1-30 letters to spell your name.')" type="text" class="form-control" placeholder="Enter first name" id="first_name" formControlName="first_name">

检查 VALIDINVALID,

firstNameValidate(ErrorTitle, ErrorMessage) {
if (this.personalForm.get('first_name').status == VALID) {
this.getSuccess("First Name Entered", "First name entered correctly");
} else {
this.toastWarning(ErrorTitle, ErrorMessage);
}
}

调用错误

在我的例子中,我决定在 toast 中显示我的错误。所以我使用 blur 来跟踪用户何时离开 input 字段。当用户移出 input 字段时,将调用 firstNameValidate() 函数并根据值显示正确的 toast有效无效。根据 response 这两个 functions 之一被触发。

toastWarning(ErrorTitle, ErrorMessage) {
var toastOptions:ToastOptions = {
title: ErrorTitle,
msg: ErrorMessage,
showClose: true,
timeout: 7000,
theme: 'bootstrap',
onAdd: (toast:ToastData) => {
console.log('Toast ' + toast.id + ' has been added!');
},
onRemove: function(toast:ToastData) {
console.log('Toast ' + toast.id + ' has been removed!');
}
};
this.toastyService.warning(toastOptions);
}

getSuccess(SuccessTitle, SuccessMessage) {
var toastOptions:ToastOptions = {
title: SuccessTitle,
msg: SuccessMessage,
showClose: true,
timeout: 5000,
theme: 'bootstrap',
onAdd: (toast:ToastData) => {
console.log('Toast ' + toast.id + ' has been added!');
},
onRemove: function(toast:ToastData) {
console.log('Toast ' + toast.id + ' has been removed!');
}
};
this.toastyService.success(toastOptions);
}

然后用户看到正确的toast/message,

成功

enter image description here

警告

enter image description here

关于angular - 在用户填写表单 Angular 2 时检查表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40966603/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com