Angular material date-picker validation

Discussão em 'Angular' iniciado por ffcabbar, Janeiro 5, 2025.

  1. ffcabbar

    ffcabbar Guest

    I was struggling to add validation to date-picker. This is a stackblitz link. You can see the codebase

    My date-picker should just allow to DD MMM YYYY format. It should not allow DD-MM-YY, DD/MM/YYYY, and such.

    I put a warning message. It works correctly. However, the date picker's own border validation does not work properly. How Can I handle this problem? The date picker should not be required.

    This is inside of the typescript file.

    export const MY_FORMATS = {
    parse: {
    dateInput: 'DD MMM YYYY',
    },
    display: {
    dateInput: 'DD MMM YYYY',
    monthYearLabel: 'MMMM YYYY',
    dateA11yLabel: 'DD MM YYYY',
    monthYearA11yLabel: 'MMMM YYYY',
    },
    };
    @Component({
    selector: 'datepicker-overview-example',
    templateUrl: 'datepicker-overview-example.html',
    styleUrls: ['datepicker-overview-example.css'],
    providers: [
    {
    provide: DateAdapter,
    useClass: MomentDateAdapter,
    deps: [MAT_DATE_LOCALE],
    },
    { provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
    ],
    })

    export class DatepickerOverviewExample {
    regexPattern = /^(([1-9])|([0][1-9])|([1-2][0-9])|([3][0-1]))(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\d{4}$/gi;

    date = new FormControl('', [Validators.pattern(this.regexPattern)]);

    getErrorMessage(val: string): string {
    const regexPattern = /^(([1-9])|([0][1-9])|([1-2][0-9])|([3][0-1]))(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\d{4}$/gi;

    const value = val.replace(/\s+/g, '');
    const isValid = regexPattern.test(value);
    console.log(isValid);
    // console.log(this.date.valid);

    if (!isValid && val !== '') {
    return 'Invalid input: Please input a string in the form of DD MMM YYYY';
    }

    return '';
    }
    }


    Here is the template.

    <mat-form-field appearance="legacy">
    <input
    matInput
    [matDatepicker]="picker"
    placeholder="Choose a date"
    #pickerInput
    [formControl]="date"
    />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
    <mat-error *ngIf="date.invalid">{{getErrorMessage(pickerInput.value)}}</mat-error>
    </mat-form-field>


    Thanks in advance!

    Continue reading...

Compartilhe esta Página