简体   繁体   English

处理格式清晰的必填字段-Angular

[英]Handling mandatory fields with form clear - Angular

Form containing a bunch of required fields are there. 包含一堆必填字段的表单在那里。 Here I am able to handle all validations and error messages perfectly. 在这里,我能够完美地处理所有验证和错误消息。 But when I clear the form, now error messaging displaying for mandatory filed's like "Field is mandatory". 但是,当我清除表单时,现在显示错误消息,显示诸如“字段为必填字段”之类的必填字段。 Here my expected behavior is when clear the form just form comes to the initial stage and not to validate any field. 在这里,我的预期行为是当清除表单时,表单才进入初始阶段,并且不验证任何字段。

I'm not getting any idea to handle this, So any idea or any suggestion is helpful for me. 我没有任何想法可以解决这个问题,因此任何想法或建议对我都有帮助。 Thanks in advance. 提前致谢。

At present, I am using Reactive forms and through a generic validator to handle validations like below. 目前,我正在使用Reactive表单并通过通用验证器来处理如下所示的验证。

You need to show error messages when: 在以下情况下,您需要显示错误消息:

(1) there is an error on a field AND (1)栏位上有错误,且

(2) the field is dirty or touched - in other words, when the field has not been tampered with. (2)场地肮脏或被触摸-换句话说,当场地未被篡改时。 Initially a field is not dirty and not touched. 最初,一个字段不脏也不被触摸。 When you change the value it becomes dirty. 更改值时,该值将变脏。 When you give the field focus and then it loses focus it is touched. 当您将重点放在字段上,然后又失去焦点时,就会被感动。 I believe resetting the form like you describe should make all fields clean again and untouched. 我相信,按照您所描述的那样重设表格应该可以使所有字段再次保持干净并保持原样。

Manage dirty and touched like this: 这样处理脏污和感动:

<label>
  First Name:
  <input formControlName="firstName" required> <!-- required is optional -->
</label>

<div *ngIf="firstName.invalid && (firstName.dirty || firstName.touched)" class="alert alert-danger">
  <div *ngIf="firstName.errors.required">Name required</div>
  <div *ngIf="firstName.errors.minlength">Name min length is 3</div>
</div>

Docs: https://angular.io/guide/form-validation 文件: https//angular.io/guide/form-validation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM