5

我有表单,我想在提交时验证日期字段,我正在使用表单生成器,我该怎么做(角度方式)?另一个问题为什么我看不到日期字段中的值 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>

4

2 回答 2

3

如果你可以使用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])],
});

演示 stackblitz.com/angular-date-validator

于 2018-07-05T07:29:06.550 回答
1

对于日期验证,您可以使用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,
      }
    );
  }
于 2018-07-05T07:55:03.417 回答