我在Angular 10项目中验证表单中的几个字段,如下所示:
<div class="question">
<div class="row">
<h5>1. Requestors Name (Your name or JHED ID)</h5><p class="required">*</p>
</div>
<input type="text" class="form-control" id="requestorName" name="requestorName" required minlength="2"
[(ngModel)]="model.requestorName" #requestorName="ngModel"/>
<div *ngIf="requestorName.invalid && (requestorName.dirty || requestorName.touched)"
class="alert">
<div *ngIf="requestorName.errors?.required">
<p class="required">Requester name is required.</p>
</div>
<div *ngIf="requestorName.errors?.minlength">
<p class="required">Requester name must be at least 2 characters long.</p>
</div>
</div>
</div>
这很好用。但是,如果用户从未像这样触摸过经过验证的字段,而是填写了表单的其余部分,那么单击"提交"仍然可以接受。
我也写了我自己的验证检查提交如下:
<div class="question">
<button class="submit col-md-2" (click)="onSubmit()">Submit</button>
</div>
validateModel(accessRequest: AccessRequestModel) {
const validityCheck = {
isValid: true,
reason: null
};
validityCheck.isValid = true;
console.log(accessRequest);
if (accessRequest) {
if (!accessRequest.requestorName) {
validityCheck.isValid = false;
validityCheck.reason = 'Requester name is required.';
return validityCheck;
} else if (!accessRequest.lname) {
validityCheck.isValid = false;
validityCheck.reason = 'Last name is required.';
return validityCheck;
}
else if (!accessRequest.fname) {
validityCheck.isValid = false;
validityCheck.reason = 'First name is required.';
return validityCheck;
}
else if (!accessRequest.department) {
validityCheck.isValid = false;
validityCheck.reason = 'Department is required.';
return validityCheck;
}
else if (!accessRequest.title) {
validityCheck.isValid = false;
validityCheck.reason = 'Job title is required.';
return validityCheck;
}
else if (!accessRequest.managerName) {
validityCheck.isValid = false;
validityCheck.reason = 'Manager name is required.';
return validityCheck;
}
else if (!accessRequest.startDate) {
validityCheck.isValid = false;
validityCheck.reason = 'Start date is required.';
return validityCheck;
}
else if (!accessRequest.accessType) {
validityCheck.isValid = false;
validityCheck.reason = 'Access type is required.';
return validityCheck;
}
}
return validityCheck;
}
这也是有效的。
但我想要的是,如果有效性检查函数返回false,如果您确实单击要应用的框,则会出现相同的错误消息。我怎么能那样做?
如果问题不清楚或者您需要更多信息,请告诉我。
似乎您正在尝试重新创建表单验证。从角度观察反应形式模块,并执行以下操作:
-
将ReactiveFormsModule导入到定义组件的模块中
-
依赖项将其注入到组件的构造函数中,如下所示:
constructor(private formBuilder: FormBuilder) {}
-
在
OnInit
方法中定义表单创建逻辑:ngOnInit() { this.myForm = this.formBuilder.group({ option1: ['', Validators.Required], ... }) }
-
根据angular提供的文档更新HTML以利用此新表单。因此,提交按钮可以定义一个
[disabled]
属性,如果表单无效,该属性会将按钮设置为禁用。表单组[{initialValue},{validator|array of validators}]中的语法控制输入的有效性。
相反,如果您仍然希望使用户即使在无效的表单输入上也能单击提交,您也可以迭代表单中的每个控件,并通过调用FormControl
对象上的setError
方法手动设置其错误状态。