Skip to content Skip to sidebar Skip to footer

Maxlength On Number Not Working

i using angular 4.3.3 maxlength 11 max span message is not showing

Solution 1:

You will need to use 'ngModelChange' to force the validation and correct a little bit the markup:

<input class="form-control" id="orderId" required maxlength="11"type="number" name="orderId" [ngModel]="orderIdModel" 
        (ngModelChange)="orderIdModel = $event + ''" #orderId="ngModel" /> 
<span *ngIf="orderId.errors?.required">
      required
</span><span *ngIf="orderId.errors?.maxlength">
    11 max
</span>

Demo

Solution 2:

I think you need to use max instead

max="99999999999"

See also How can I limit possible inputs in a HTML5 "number" element?

min and max are only available for model-driven forms by default.

I created a directive that makes max available to template-driven forms, by copying and adapting the source of the maxLength validator from https://github.com/angular/angular/blob/fcadbf4bf6d00ea5b250a8069e05b3e4bd000a29/packages/forms/src/directives/validators.ts

Plunker example

import {Component, NgModule, VERSION, Directive, forwardRef, Input} from'@angular/core'import {BrowserModule} from'@angular/platform-browser'import {FormsModule, Validators, NG_VALIDATORS} from'@angular/forms'
exportconstMAX_VALIDATOR: any = {
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() =>MaxValidator),
  multi: true
}

@Directive({
  selector: '[max][formControlName],[max][formControl],[max][ngModel]',
  providers: [MAX_VALIDATOR],
  host: {'[attr.max]': 'max ? max : null'}
})
exportclassMaxValidatorimplementsValidator,
    OnChanges {
  private_validator: ValidatorFn;
  private_onChange: () =>void;

  @Input() max: string;

  ngOnChanges(changes: SimpleChanges): void {
    if ('max'in changes) {
      this._createValidator();
      if (this._onChange) this._onChange();
    }
  }

  validate(c: AbstractControl): ValidationErrors|null {
    returnthis.max != null ? this._validator(c) : null;
  }

  registerOnValidatorChange(fn: () =>void): void { this._onChange = fn; }

  private_createValidator(): void {
    this._validator = Validators.max(parseInt(this.max, 10));
  }
}
@Component({
  selector: 'my-app',
  template: `
    <form #orderId="ngForm" ngForm>
      <input type="number" class="form-control" id="orderId"
          [(ngModel)]="orderIdModel"  name="orderId" #orderId="ngModel" required min="10" max="999"  />
          <div>errors: {{orderId.errors | json}} </div>
      <div *ngIf="orderId.errors">
        <span *ngIf="orderId.errors.required"class="not-valid">required</span>
        <span *ngIf="orderId.errors.max"class="not-valid"> 11 max</span>
      </div> 
    </form>
  `,
})
exportclassApp {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}
@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App, MaxValidator ],
  bootstrap: [ App ]
})
exportclassAppModule {}

Post a Comment for "Maxlength On Number Not Working"