Custom validation for positive numbers

落花浮王杯 提交于 2019-12-13 14:00:40

问题


I was trying to find the information, if there are any built-in validators, that check if the input is a positive number?

I was trying to build the following:

static nonZero(control:Control) {
    if (Number(control.value) < 0) {
        control.setErrors({nonZero: true})
    } else {
    control.setErrors(null)
    }
}

However, I didn't know how to use it in my form builder:

this.form = _formBuilder.group({
            field:['', Validators.required]})

What am I doing wrong?


回答1:


You can configure it this way by leveraging the Validators.compose method:

this.form = _formBuilder.group({
        field:['', Validators.compose([
                     Validators.required, nonZero ])
        ]});

This allows you to define your two synchronous validators for the field.

Edit

I would implement the validator this way:

static nonZero(control:Control):{ [key: string]: any; } {
  if (Number(control.value) < 0) {
    return {nonZero: true};
  } else {
    return null;
  }
}



回答2:


Little refactored:

 export function positiveNumberValidator(): ValidatorFn {
      return (control: AbstractControl): { [key: string]: any } => {
        const isNotOk = Number(control.value) < 0;
        return isNotOk ? { nonPositive: { value: control.value } } : null;
      };
 }

and if you want to use it in template as Directive:

import { Directive, Input } from '@angular/core';
import { ValidatorFn, AbstractControl, NG_VALIDATORS, Validator } from '@angular/forms';

@Directive({
  selector: '[prePositiveNumber]',
  providers: [{ provide: NG_VALIDATORS, useExisting: PositiveNumberDirective, multi: true }]

})
export class PositiveNumberDirective implements Validator {

  validate(c: AbstractControl): { [key: string]: any; } {
    return positiveNumberValidator()(c);
  }
}

export function positiveNumberValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } => {
    const isNotOk = Number(control.value) < 0;
    return isNotOk ? { nonPositive: { value: control.value } } : null;
  };
}

Template:

 <input type="number"
        class="full"
        name="shipmentVolume"
        required
        prePositiveNumber
        [(ngModel)]="someModel" />

When using as Reactive forms you can compose validators, but also it can be used without compose:

this.form = _formBuilder.group({
        field:['', Validators.required, positiveNumberValidator()] });



回答3:


I'd use same compose methodology, but implement a min function, that you can pass 1 too.

import { ValidatorFn, AbstractControl } from '@angular/forms';
export function min(min: Number): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      const input = control.value,
            isValid = input < min;
      if(isValid) 
          return { 'minValue': {min} }
      else 
          return null;
    };
}


this.pnFG = this.fb.group({
  pageNumberInput: [this.pageNumber, 
                    Validators.compose([
                        Validators.required,
                        min(1)
                    ])
                  ]
});



回答4:


You can combine min Validator and a regex pattern Validator:

 field: ['', [Validators.required, Validators.min(1), Validators.pattern('^(0|[1-9][0-9]*)$')]],



回答5:


You could do something like,

.js

  orderFormGroup = new FormGroup({
    weight: new FormControl('', [Validators.required, Validators.min(0)])
  });

This would allow less than and equal to zero values, if you want values more than zero then you could mention Validators.min(0.1)

.html

  <input type="number" step="0.1" name="orderWeight" formControlName="weight" max="35" min="0" class="clr-input form-control">

Note that the min="0" would only ensure that the front-end increase or decrease wouldnt go passed 0. The actual input validation is handled in .js




回答6:


<input type="number" ng-model="size" name="size" min="0" max="10" integer />

Easy as that!



来源:https://stackoverflow.com/questions/38098822/custom-validation-for-positive-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!