问题描述
我是棱角材料2的新手,并试图验证出生日期(DOB)表单字段,例如官方Angular网站中的以下示例
I'm new to angular material 2, and trying to validate the Date of Birth(DOB) form field like following example in Official Angular Website
因此,在 input-errors-example.html 中,我添加了如下所示的表单字段
So in input-errors-example.html I added form field like following
<md-form-field class="example-full-width">
<input mdInput [mdDatepicker]="picker" placeholder="Choose a date" [formControl]="dobFormControl" onkeypress='return (event.charCode >= 48 && event.charCode <= 57) || event.charCode == 47' maxlength="10">
<md-datepicker-toggle mdSuffix [for]="picker"></md-datepicker-toggle>
<md-datepicker #picker></md-datepicker>
<md-error *ngIf="dobFormControl.hasError('required') || dobFormControl.hasError('pattern')">
Please enter a valid Date
</md-error>
</md-form-field>
然后在 input-errors-example.ts 文件中,我添加了自定义正则表达式以接受 MM/DD/YYYY 格式
then in input-errors-example.ts file I added custom regular expression to accept MM/DD/YYYY format
import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';
const DOB_REGEX = /^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
@Component({
selector: 'input-errors-example',
templateUrl: 'input-errors-example.html',
styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {
dobFormControl = new FormControl('', [
Validators.required,
Validators.pattern(DOB_REGEX)
]);
}
对于上面的示例,这是 Plunker ,但是在这里我无法选择日期或看不到任何错误消息.
This is the Plunker for above example, but here I cannot select a date or cannot see any error message.
推荐答案
要使FormControl与正则表达式一起使用,必须使用null
而不是''空字符串来实例化FormControl:
For your FormControl to work with your regex, you have to instantiate the FormControl with null
instead of '' empty string:
dobFormControl = new FormControl(null, [
Validators.required,
Validators.pattern(DOB_REGEX)
]);
您现在正在工作的朋克此处
Your working now plunker here
这篇关于使用formcontrol验证md-datepicker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!