我正在尝试验证角度为6的表格,但不起作用。我的代码在stackblitz中。 如何验证该表格以及如何显示错误消息? https://stackblitz.com/edit/angular-6-reactive-form-validation-ctzf7f?file=app/app.component.html
<div class="col-md-4">
<label>
<input type="radio" name="bhk" formControlName="onebhk" value="yes" /> 1 BHK
</label>
<label>
<input type="radio" name="bhk" formControlName="onebhk" value="no" /> 2 BHK
</label>
</div>
TS:
this.registerForm=new FormGroup({
userType:new FormControl('',Validators.compose([
Validators.required
])),
modalType:new FormControl('',Validators.required),
place:new FormControl('',Validators.required),
onebhk:new FormControl('',Validators.required),
min:new FormControl('',Validators.compose([
Validators.required,
Validators.min(200)
])),
max:new FormControl('',Validators.compose([
Validators.required,
Validators.max(2000)
]))
})
答案 0 :(得分:1)
您必须在提交时将提交标志设置为true,并在以下情况下检查错误:
<p style="color:red" *ngIf="!registerForm.controls.userType.valid &&
submitted">Required</p>
这是您的解决方案。 https://stackblitz.com/edit/angular-6-reactive-form-validation-cxzbr6?file=app/app.component.ts
答案 1 :(得分:0)
您可以使用创建表单组并使用formcontrol来验证数据。 Stackblitz https://stackblitz.com/edit/angular-6-reactive-form-validation-cy6avn
示例
component.ts
constructor(private fb: FormBuilder) { }
formSubmitted: boolean;
testForm = this.fb.group({
field1: ['', [Validators.required]],
field2: ['', [Validators.required]],
});
isFieldValid(field: string) {
return (
this.testForm.get(field).errors && this.testForm.get(field).touched ||
this.testForm.get(field).untouched &&
this.formSubmitted && this.testForm.get(field).errors
);
}
onSubmit() {
this.formSubmitted = true;
if (this.testForm.valid) {
alert('VALID');
} else {
alert('NOT VALID');
}
}
component.html
<form [formGroup]="testForm">
<div class="form-group">
<label>First Name:</label>
<input type="text" formControlName="field1">
<div *ngIf="isFieldValid('field1')">
<div style="font-size: 12px; color: red">
NOT VALID
</div>
</div>
</div>
<div class="form-group">
<label>Last Name:</label>
<input type="text" formControlName="field2">
<div *ngIf="isFieldValid('field2')">
<div style="font-size: 12px; color: red">
NOT VALID
</div>
</div>
</div>
</form>
<div>
<button (click)="onSubmit()">Submit</button>
</div>