gpt4 book ai didi

validation - 如何在 angularJS2 中使用 ReactiveFormsModule 验证单选按钮?

转载 作者:太空狗 更新时间:2023-10-29 18:16:42 35 4
gpt4 key购买 nike

我是 angularJS2 的新手,我正在尝试使用 ReactiveFormsModule 学习 angularJS2 表单中的验证。现在我一直在研究如何在 angularJS2 中验证单选按钮

这是我的组件代码

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

import { userDetails } from '../app/userDetails'

@Component({
selector: 'user-validation',
templateUrl: '../app/app.template.html'
})
export class userComponent implements OnInit {
constructor(private fb: FormBuilder) { }
userForm: FormGroup;
users = new userDetails();
ngOnInit(): void {
this.buildForm();
}

buildForm(): void {
this.userForm = this.fb.group({
'username': [this.users.username, [
Validators.required,
Validators.minLength(4),
Validators.maxLength(24)
]
]
});

this.userForm.valueChanges
.subscribe(data => this.onValueChanged(data));

this.onValueChanged(); // (re)set validation messages now
}
onValueChanged(data?: any) {
if (!this.userForm) { return; }
const form = this.userForm;

for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);

if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
onSubmit() {
this.users = this.userForm.value;
}
formErrors = {
'username': ''
};

validationMessages = {
'username': {
'required': 'Name is required.',
'minlength': 'Name must be at least 4 characters long.',
'maxlength': 'Name cannot be more than 24 characters long.',
'forbiddenName': 'Someone named "Bob" cannot be a hero.'
}
};
}

HTML代码

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" class="form-group">
<label>Gender</label>
<label><input type="radio" name="gender" /> Male</label>
<label><input type="radio" name="gender" />Female</label>
<button type="submit" [disabled]="!userForm.valid" class="btn btn-success">Submit</button>
</form>

我无法在 angularJS2 中找到任何与单选按钮验证相关的文档,即使在这里 angular.io

最佳答案

根据您的代码,您可以这样使用。

this.userForm = this.fb.group({
'username': [this.users.username, [
Validators.required,
Validators.minLength(4),
Validators.maxLength(24)
]],
'gender': [this.users.gender, Validators.required]
});

HTML 模板:

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" class="form-group">
<label>Gender</label>
<label><input type="radio" formControlName="gender" value="M" /> Male</label>
<label><input type="radio" formControlName="gender" value="F" />Female</label>
<button type="submit" [disabled]="!userForm.valid" class="btn btn-success">Submit</button>
</form>

关于validation - 如何在 angularJS2 中使用 ReactiveFormsModule 验证单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41933624/

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