Angular 2 custom validation for numbers and decimal values
Something like this should work
import { AbstractControl, ValidatorFn } from '@angular/forms';
export class NumberValidators {
static isNumberCheck(): ValidatorFn {
return (c: AbstractControl): {[key: string]: boolean} | null => {
let number = /^[.\d]+$/.test(c.value) ? +c.value : NaN;
if (number !== number) {
return { 'value': true };
}
return null;
};
}
}
can use ng-pattern validation
ng-pattern="^[0-9]+(.[0-9]{0,2})?$"
can you please check once like this
<label for="upperbeltposition"
class="col-md-6 col-form-label"
name="number">
Upper Belt
Position (mm)
<span class="required">*</span>
</label>
<div class="col-md-5">
<input
class="form-control input-transparent "
id="upperbeltposition"
type="text"
formControlName="upperbeltposition"
data-parsley-trigger="blur"
required="required"
data-parsley-type="number"/>
<span
ng-show="submitForm && platformxposition
.number.$error.pattern">This value should be a valid number
</span>
</div>
You must add your form name. and input field name.$error.pattern
Instead of creating a custom validator, you can also simply use the Validators.pattern
https://angular.io/api/forms/Validators#pattern:
['', [Validators.required, Validators.pattern(/^[.\d]+$/)]]