formbuilder angular 9 – 日期验证器问题

huangapple go评论111阅读模式
英文:

formbuilder angular 9 - problem with date validator

问题

以下是您要翻译的内容:

"I have a task to divided 2 message for datetime input:

  • Date is require
  • Out of date (like 30/02/2023 is not a valid date)

But the problem is when I use validator with formbuilder. The date return is validate before I click on the button submit. So when I click on the submit button the date always return null if it not valid (it mean I can not set 2 different condition because 2 condition is the same null value). So I can not setError for 2 message control in formbuilder when click on submit button.

Library

import * as dateFormat from "dateformat";

.ts

updateForm: FormGroup;

constructor(
  private fb: FormBuilder) { }

createForm() {
  let now = new Date();
  this.updateForm = this.fb.group({
    date: [
      dateFormat(now, "yyyy-mm-dd"),
      [Validators.required],
    ],
  });
}

ngOnInit(): void {
  this.createForm()
}

onSubmit() {
  console.log(this.updateForm.value.date)
  //always null if date not valid
}

.html

<input type=&quot;date&quot; class=&quot;form-control input is-primary&quot; formControlName=&quot;ngayApDung&quot;
    [ngClass]=&quot;{ &#39;is-invalid&#39;: submitted &amp;&amp; f.date.errors }&quot; cdkFocusInitial />
<div *ngIf=&quot;submitted &amp;&amp; f.date.errors&quot; class=&quot;help is-danger&quot;>
    <div *ngIf=&quot;f.date.errors.required&quot; translate>
        date is required
    </div>
</div>
英文:

I have a task to divided 2 message for datetime input:

  • Date is require
  • Out of date (like 30/02/2023 is not a valid date)

But the problem is when I use validator with formbuilder. The date return is validate before I click on the button submit. So when I click on the submit button the date always return null if it not valid (it mean I can not set 2 different condition because 2 condition is the same null value). So I can not setError for 2 message control in formbuilder when click on submit button.

Library

import * as dateFormat from &quot;dateformat&quot;;

.ts

    updateForm: FormGroup;

  constructor(
    private fb: FormBuilder) { }

  createForm() {
    let now = new Date();
    this.updateForm = this.fb.group({
      date: [
        dateFormat(now, &quot;yyyy-mm-dd&quot;),
        [Validators.required],
      ],

    });
  }

  ngOnInit(): void {
    this.createForm()
  }

  onSubmit() {
    console.log(this.updateForm.value.date)
    //alway null if date not valid
  }

.html

&lt;input type=&quot;date&quot; class=&quot;form-control input is-primary&quot; formControlName=&quot;ngayApDung&quot;
    [ngClass]=&quot;{ &#39;is-invalid&#39;: submitted &amp;&amp; f.date.errors }&quot; cdkFocusInitial /&gt;
&lt;div *ngIf=&quot;submitted &amp;&amp; f.date.errors&quot; class=&quot;help is-danger&quot;&gt;
    &lt;div *ngIf=&quot;f.date.errors.required&quot; translate&gt;
        date is required
    &lt;/div&gt;
&lt;/div&gt;

答案1

得分: 0

HTML 输入元素具有 validityState 类,其中包含许多属性。
当您输入错误的日期时,badInput 属性的值为 true

formbuilder angular 9 – 日期验证器问题

formbuilder angular 9 – 日期验证器问题

因此,您可以通过添加额外的辅助函数来实现您想要的功能:

首先添加一个新的辅助变量

badInput: boolean = false;

表单仅包含所需的验证

let now = new Date();
this.updateForm = new FormGroup({
      date_new: new FormControl(now, [
        Validators.required,
      ]),
    });

添加一个新的辅助函数

check(e: any){
  const target = e.target as HTMLInputElement;
  if (target.validity.badInput){
    this.badInput = target.validity.badInput 
  }
  else{
    this.badInput = false
  }
}

HTML

<input
      type="date"
      class="form-control input is-primary"
      formControlName="date_new"
      [(ngModel)]="now"
      cdkFocusInitial
      formtarget="date : 'yyyy-MM-dd'"
      (keyup)="check($event)"
      />

  <div *ngIf="updateForm.controls['date_new'].errors && !badInput">请输入日期
</div>
  <div *ngIf="updateForm.controls['date_new'].errors && badInput">无效的日期
</div>

您需要使用 updateForm.controls['date_new'].errors 来仅在出现错误时显示 <div>,而 badInput 会在 HTMLInputElement 的更改后发生变化。

英文:

The HTML input element has a validityState class with many attributes.
The badInput attribute is true when you put a wrong date.

formbuilder angular 9 – 日期验证器问题

formbuilder angular 9 – 日期验证器问题

So you can achieve what you want by adding an extra helper function:

Firstly add a new helper variable

badInput: boolean = false;

Form has only the required Validation

let now = new Date();
this.updateForm = new FormGroup({
      date_new: new FormControl(now, [
        Validators.required,
      ]),
    });

add a new helper function

check(e: any){
  const target = e.target as HTMLInputElement;
  if (target.validity.badInput){
    this.badInput = target.validity.badInput 
  }
  else{
    this.badInput = false
  }
}

html

&lt;input
      type=&quot;date&quot;
      class=&quot;form-control input is-primary&quot;
      formControlName=&quot;date_new&quot;
      [(ngModel)]=&quot;now&quot;
      cdkFocusInitial
      formtarget=&quot;date : &#39;yyyy-MM-dd&#39;&quot;
      (keyup)=&quot;check($event)&quot;
      /&gt;

  &lt;div *ngIf=&quot;updateForm.controls[&#39;date_new&#39;].errors &amp;&amp; !badInput&quot;&gt;Please enter a date
&lt;/div&gt;
  &lt;div *ngIf=&quot;updateForm.controls[&#39;date_new&#39;].errors &amp;&amp; badInput&quot;&gt;Invalid date
&lt;/div&gt;

You need updateForm.controls[&#39;date_new&#39;].errors to display divs only on errors and the badInput changes after the change of the HTMLInputElement

huangapple
  • 本文由 发表于 2023年6月12日 12:25:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453649.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定