Home > Net >  Angular input how short this function?
Angular input how short this function?

Time:11-22

phoneError(): string {
    return this.userForm.get('phonenumber').hasError('required')
      ?  $localize`:|Validation message: Only number`
      : this.userForm.get('phonenumber').hasError('minlength') ||
        this.userForm.get('phonenumber').hasError('maxLength')
      ? $localize`:|Validation message: 3 min`
      : '3 min';
  }


    <mat-form-field appearance="fill">
      <input matInput formControlName="phonenumber" required />
      <mat-label>Phone number</mat-label>
      <mat-error *ngIf="'userForm.get('phonenumbern').invalid">{{ phoneError() }}</mat-error>
    </mat-form-field>
  </div>

How short this ? those are messages for input required

I want functional input if somone don't put anything in input I want see on Required: Only number. If someone enters too many digits or too few I want see 3 min

CodePudding user response:

simplify the statement

phoneError(): string {

   const control = this.userForm.get('phonenumber')

   if(control.hasError('required')) {
     return  $localize`:|Validation message: Only number`
   }else if(control.hasError('maxLength')){
     return  $localize`:|Validation message: 3 min`
   }
   return `3 min`
     
}

CodePudding user response:

You can use a custom error

  errorPhone(control:AbstractControl){
    if (!control.value)
        return {error:"Only number"}
   
    if (control.value.length!=3)
        return {error:"3 numbers"}

    return null
   }

Then in input you can use simply

<mat-error >{{ userForm.get('phonenumbern')?.error}}</mat-error>

Remember that the mat-error, by defect, only is showed when the control is invalid and touched

  • Related