以 Angular 6 反应形式预填充和验证日期 [英] Pre-populating and validating date in Angular 6 reactive form

查看:32
本文介绍了以 Angular 6 反应形式预填充和验证日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除我的日期外,所有其他字段都已预先填充.

出于测试目的,我将日期硬编码为 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': 新的 FormControl(project.InstallDate),'closeDate': new FormControl(project.CloseDate),'status': new FormControl(project.Status, [Validators.required, ForbiddenProjectStatusValidator.forbiddenProjectStatus])});//设置日期和状态下拉菜单this.projectForm.patchValue({'预期日期':'08/17/2018','安装日期':'08/18/2018','closeDate': '08/19/2018',状态":项目.状态?项目.状态:"});

html

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

基本上,

如何

  • 预填充日期
  • 验证日期为 MM/dd/yyyy(不需要任何日期).用户可能无法输入或选择完整日期

更新 1:

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

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

如何将当前日期转换为 YYYY-MM-DD 格式,角度为 2

如何格式化 JavaScript 日期

这对我有用

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}')])

解决方案

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

import { FormControl } from "@angular/forms";从时刻"导入 * 作为时刻;导出函数 DateValidator(format = "MM/dd/YYYY"): any {return (control: FormControl): { [key: string]: any } =>{const val = moment(control.value, format, true);如果 (!val.isValid()) {返回 { invalidDate: true };}返回空;};}

然后在表单控件中使用

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

<块引用>

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

您不能在 FormControl 中使用管道.最简单的方法是先转换为目标格式,然后再对值进行修补以形成

this.projectForm.patchValue({'expectedDate': moment(model.expectedDate).format('MM/dd/YYYY'),...});

All the rest of the fields are getting pre-populated except date for me.

For testing purposes, i have hard coded the date as MM/DD/YYYY.

From the DB, i'll get Date and Time, so i'll need to use the pipe to make it MM/DD/YYYY (am i correct about this?)

component code

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">

Due to input type date, browser shows calendar control.

So basically,

How to

  • pre-populate date
  • validate date that it is MM/dd/yyyy (none of the dates are required). User might not enter or select full date

Update 1:

selected answer is perfect, it details the use of moment but for now i have gone with simplest solution...

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

This is what is working for me

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

or current as

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

or

expectedDate: '2018-08-08' 

the date has to be YYYY-MM-DD.

For validation, pattern is working

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

解决方案

You can define a custom validator for date. Use date time that support date validation such as 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;
  };
}

Then use it in form control

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

From the DB, i'll get Date and Time, so i'll need to use the pipe to make it MM/DD/YYYY (am i correct about this?)

You can't use pipe in FormControl. The simplest way is converting to target format before patching value to form

this.projectForm.patchValue({
  'expectedDate': moment(model.expectedDate).format('MM/dd/YYYY'),
  ...
});

这篇关于以 Angular 6 反应形式预填充和验证日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆