使用表单构建器的角度5验证日期字段

时间:2018-07-05 07:09:45

标签: angular validation angular5 formbuilder angular-validator

我有表格,我想在提交时验证日期字段,我使用的是Form Builder,我该怎么做(角度方式)? 另一个问题为什么我在日期字段中看不到值published_date? 我试图搜索,但找不到输入日期字段的解决方案。

unamePattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
  ngOnInit() {
    this.book = 
      {
        id: 55,
        author_name : "vv",
        published_date :  new Date('01/02/2018'),
        title : "cc"
      };
      
      this.form = this.formBuilder.group({
        title : ['', Validators.required],
        author : ['', Validators.required],
        datePublish: ['', Validators.pattern(this.unamePattern)],
        }
      );
  }
<input 
            [(ngModel)]="book.published_date"
            id="dateOfBirth" 
            class="form-control" 
            placeholder="yyyy-mm-dd" 
            name="dp" 
            ngbDatepicker 
            formControlName="datePublish"
            #dp="ngbDatepicker">
            
          <div class="input-group-append">
            <button class="btn btn-outline-secondary" (click)="dp.toggle()" type="button">
                <i class="fa fa-calendar" aria-hidden="true"></i>
            </button>
          </div>

2 个答案:

答案 0 :(得分:2)

如果您可以使用momemt(),那么很容易掌握日期时间,您可以编写自己的验证器为

import {AbstractControl} from '@angular/forms';
import * as moment from 'moment';

export class YourValidator {
  static dateVaidator(AC: AbstractControl) {
    if (AC && AC.value && !moment(AC.value, 'YYYY-MM-DD',true).isValid()) {
      return {'dateVaidator': true};
    }
    return null;
  }
}

在表单对象中,您可以像

一样使用它
import {YourValidator} from "....";

this.form = this.formBuilder.group({
    title : ['', Validators.required],
    author : ['', Validators.required],
    datePublish: ['', Validators.compose([Validators.required, YourValidator.dateVaidator])],
});

Demo stackblitz.com/angular-date-validator

答案 1 :(得分:0)

对于日期验证,您可以使用ng4-validators

npm i ng4-validators --save

导入和使用:

import { CustomValidators } from 'ng4-validators';

ngOnInit() {
  this.book = 
    {
      id: 55,
      author_name : "vv",
      published_date :  new Date('01/02/2018'),
      title : "cc"
    };

    this.form = this.formBuilder.group({
      title : ['', Validators.required],
      author : ['', Validators.required],
      datePublish: ['', CustomValidators.date,
      }
    );
  }