我使用angular 4.3.3
maxlength 11 max span message未显示
<input type="number" class="form-control" id="orderId" [(ngModel)]="orderIdModel" name="orderId" #orderId="ngModel" required maxLength="11" />
<div *ngIf="orderId.errors">
<span *ngIf="orderId.errors.required"class="not-valid">required</span>
<span *ngIf="orderId.errors.maxlength"class="not-valid"> 11 max</span>
</div>
答案 0 :(得分:2)
您需要使用'ngModelChange'来强制验证并更正标记:
<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 强>
答案 1 :(得分:1)
我认为您需要使用 max
max="99999999999"
另见How can I limit possible inputs in a HTML5 "number" element?
min
和max
默认情况下仅适用于模型驱动的表单。
我创建了一个指令,通过复制和调整来自https://github.com/angular/angular/blob/fcadbf4bf6d00ea5b250a8069e05b3e4bd000a29/packages/forms/src/directives/validators.ts
的max
验证程序的来源,使maxLength
可用于模板驱动的表单
import {Component, NgModule, VERSION, Directive, forwardRef, Input} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {FormsModule, Validators, NG_VALIDATORS} from '@angular/forms'
export const MAX_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'}
})
export class MaxValidator implements Validator,
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 {
return this.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>
`,
})
export class App {
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`
}
}
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ App, MaxValidator ],
bootstrap: [ App ]
})
export class AppModule {}