matth3o matth3o - 1 year ago 198
Dart Question

dart angular2 - validate number in form

Is there a builtin validator in Angular2 to validate a number input? The attributes "min" and "max" do not seem to be interpreted by the validator.

Thanks for your help.

My input in my template :

<input id="nbLuggage" name="nbLuggage" classe="form-control"
type="number" min="1" max="15"
[(ngModel)]="form.nbLuggage" ngControl="nbLuggage" required>

If I enter "20", my input still is "ng-valid".

I use angular2: 2.0.0-beta.21.

Answer Source

No, but you can create your own, something like this

const NUMBER_VALIDATOR = const Provider(NG_VALIDATORS, useExisting: NumberValidator, multi: true);

    providers: const [NUMBER_VALIDATOR])
class NumberValidator implements Validator {
  ValidatorFn _validator;

  NumberValidator(@Attribute("min") String minStr, @Attribute("max") String maxStr) {
    final num min = minStr == null ? null : num.parse(minStr);
    final num max = maxStr == null ? null : num.parse(maxStr);
    this._validator = NumberValidators.minMaxNumberValidator(min, max);
  Map<String, dynamic> validate(AbstractControl c) {
    return this._validator(c);

abstract class NumberValidators {

  static ValidatorFn minMaxNumberValidator(num min, num max) {
    return (AbstractControl control) {
      if (Validators.required(control) != null) {
        return null;
      final num value = control.value;
      if (value != null) {
        if (min != null && value < min) {
          return {"min": {"required": min, "actual": value}};
        if (max != null && value > max) {
          return {"max": {"required": max, "actual": value}};
      return null;

And then you should add NumberValidator to your component's directives list. Also, if you want to bind variables to min and max, you need not just to pass values into constructor, but re-initialize _validator callback on each min and max attribute set. And in fact may be better to split it to two separate validators (in my case there is also step validator, that can not work separately).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download