材料DatePicker格式验证

时间:2018-02-22 14:31:38

标签: angular validation datepicker angular-material angular5

所以我正在做一个Angular 5应用程序并尝试对Material DatePicker进行验证(来自Material.Angular.IO)。到目前为止适用于功能部分,但我也想避免用户可以写随机文本或只是一两个数字,我的意思是,强迫他写一个正确的格式。我尝试过验证器的模式方法,但没有任何成功。有任何想法吗?

HTML

<mat-form-field fxFlex="50">
          <input matInput [matDatepicker]="picker" placeholder="Fecha de nacimiento" name="fechanacimiento"
                 [formControl]="fechanacimiento" [errorStateMatcher]="matcher">
          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
          <mat-datepicker #picker></mat-datepicker>
          <mat-error *ngIf="fechanacimiento.hasError('required')">
            La fecha de nacimiento<strong> obligatorio</strong>
          </mat-error>
          <mat-error *ngIf="fechanacimiento.hasError('pattern')">
            La fecha de nacimiento<strong> no tiene el formato correcto</strong>
          </mat-error>
        </mat-form-field>

控制器:

  fechanacimiento = new FormControl('', [
Validators.required,
Validators.pattern('\\d{1,2}\\/\\d{1,2}\\/\\d{4}')]);

export class MyErrorStateMatcher implements ErrorStateMatcher {isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));}}

0 个答案:

没有答案
相关问题