Angular 6反应形式的预填充和验证日期

时间:2018-08-18 03:35:52

标签: angular6 angular-validation

除日期外,所有其他字段均已预先填充。

出于测试目的,我将日期硬编码为MM / DD / YYYY。

从数据库中,我将获得日期和时间,因此我需要使用管道将其设置为MM / DD / YYYY(我对此是否正确?)

组件代码

this.projectForm = new FormGroup({
  'name': new FormControl(project.ProjectName, [Validators.required, Validators.minLength(3), Validators.maxLength(20)]),
  'customerName': new FormControl(project.CustomerName, [Validators.required, Validators.minLength(3), Validators.maxLength(20)]),
  'soNo': new FormControl(project.CustomerOrderId, [Validators.required, Validators.maxLength(30)]),

  'poNo': new FormControl({ value: project.PurchaseOrderId, disabled: true }),

  'expectedDate': new FormControl({ value: project.ExpectedDate, disabled: true }), 
  'installDate': new FormControl(project.InstallDate),
  'closeDate': new FormControl(project.CloseDate),

  'status': new FormControl(project.Status, [Validators.required, ForbiddenProjectStatusValidator.forbiddenProjectStatus])
});


//setting the dates and status dropdown
this.projectForm.patchValue({
  'expectedDate': '08/17/2018',
  'installDate': '08/18/2018',
  'closeDate': '08/19/2018',
  'status': project.Status ? project.Status : "" 
});

html

<input type="date" id="expectedDate" class="form-control" placeholder="Expected Date" formControlName="expectedDate">

由于输入日期类型,浏览器显示日历控件。

基本上,

操作方法

  • 预填充日期
  • 确认日期为MM / dd / yyyy(不需要日期)。用户可能无法输入或选择完整日期

enter image description here

更新1:

选择的答案是完美的,它详细说明了片刻的用法,但现在我已经有了最简单的解决方案...

https://css-tricks.com/prefilling-date-input/

how to convert current date to YYYY-MM-DD format with angular 2

How to format a JavaScript date

这就是对我有用的

expectedDate: new Date('08/08/2018').toISOString().substr(0, 10)

或当前为

expectedDate: new Date(new Date().toLocaleDateString("en-US")).toISOString().substr(0, 10) 

expectedDate: '2018-08-08' 

日期必须为YYYY-MM-DD。

为了验证,模式有效

'expectedDate': new FormControl(project.InstallDate, [Validators.pattern('[0-9]{4}-[0-9]{2}-[0-9]{2}')])

1 个答案:

答案 0 :(得分:1)

您可以定义日期的自定义验证器。使用支持日期验证的日期时间,例如moment

import { FormControl } from "@angular/forms";
import * as moment from "moment";

export function DateValidator(format = "MM/dd/YYYY"): any {
  return (control: FormControl): { [key: string]: any } => {
    const val = moment(control.value, format, true);

    if (!val.isValid()) {
      return { invalidDate: true };
    }

    return null;
  };
}

然后在表单控件中使用它

{
   ...
  'closeDate': new FormControl(project.CloseDate, [ DateValidator() ]),
}
  

从数据库中,我将获得日期和时间,因此我需要使用管道将其设置为MM / DD / YYYY(我对此是否正确?)

您不能在FormControl中使用管道。最简单的方法是在将值修补为表格

之前转换为目标格式
this.projectForm.patchValue({
  'expectedDate': moment(model.expectedDate).format('MM/dd/YYYY'),
  ...
});