Angular: Empty input condition for string validation not working

Discussão em 'Angular' iniciado por mrks, Novembro 13, 2024.

  1. mrks

    mrks Guest

    The following functions are defined in an Angular component:

    handleInput(event) {
    // Validate the input
    if (event.target.value.length >= 8) {
    this.validate(event.target.value);
    }
    }
    // Validation logic for provider NG_VALIDATORS will
    // Logic for NG_VALIDATORS provider, returns validation result to parent form
    /** @internal */
    validate(control) {
    const value = control.value || control;
    if (this.required && value.replace(/\s+/g, '').length === 0) {
    this.hasError = this.control.touched || this.control.dirty;
    this.errorText = [{ message: this.requiredErrorMessage }];
    return this.required ? { required: 'date required' } : null;
    }
    if (!value) {
    this.hasError = false;
    return null;
    }
    const [day, month, year] = value.split('.').map(Number);
    if (day && month && year && value.length === 10) {
    const date = new Date(year, month - 1, day);
    const isDateValid = !isNaN(date.getTime()) && date.getFullYear() === year && date.getMonth() + 1 === month && date.getDate() === day;
    this.hasError = !isDateValid || date > this.maxDate || date < this.minDate;
    if (this.hasError) {
    this.hasError = true;
    this.errorText = [{ message: this.validationErrorMessage }];
    return { invalid: 'date invalid' };
    }
    }
    this.hasError = false;
    return null;
    }


    This is the corresponding custom input field:


    <input
    #input
    type="text"
    mask="00.00.0000"
    autocomplete="off"
    (input)="handleInput($event)"
    [(ngModel)]="value"
    />




    The input field will add with ngx-mask a mask for a date field in DD.MM.YYYY format.

    Problem:

    When the component is rendered, the following error is thrown:


    ERROR TypeError: value.split is not a function
    ​

    For this line of code: const [day, month, year] = value.split('.').map(Number);

    I already tried to fix it with

    if (!value) {
    this.hasError = false;
    return null;
    }


    The error is shown when the component is rendered of if a string was entered in the input field and then the input has been deleted (empty input field).

    Continue reading...

Compartilhe esta Página