numberValidation.ts
import { FormGroup, FormControl, Validators,AbstractControl,ValidatorFn } from '@angular/forms';
export function numberValidation(prms:any = {}): ValidatorFn {
return (control: FormControl): {[key:string]: any} => {
let val: number = control.value;
if(isNaN(val) || /\D/.test(val.toString())) {
return {"number": true};
} else if(!isNaN(prms.min) && !isNaN(prms.max)) {
return val < prms.min || val > prms.max ? {"number": true} : null;
} else if(!isNaN(prms.min)) {
return val < prms.min ? {"number": true} : null;
} else if(!isNaN(prms.max)) {
return val > prms.max ? {"number": true} : null;
} else {
return null;
}
};
}
in Your Component import numberValidation File
import { numberValidation } from '../../common/validation/numberValidation';
Angular 6 Check only Number
VPNRemotePort: new FormControl('', [numberValidation()])
Angular 6 Validation Check only Min Number Validation
VPNRemotePort: new FormControl('', [numberValidation({min:1})])
Angular 6 Validation Check only Max Number Validation
VPNRemotePort: new FormControl('', [numberValidation({max:1})])
Angular 6 Validation Check only Min and MAx Number Validation
VPNRemotePort: new FormControl('', [numberValidation({min:1,max:65535})])
Component Html Use Example key name is number
<div *ngIf="VPNRemotePort.invalid && VPNRemotePort.dirty" class="text-danger padding-2">
<div *ngIf="VPNRemotePort.errors.number">
{{getVPNRemotePortInvalidErrorMsg}}
</div>
</div>
You Can Also Write a Validation function in Same Component
VpnRemotePortValidator(portValue: String): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} | null => {
let vpnRemotePort = parseInt(control.value);
if (isNaN(vpnRemotePort) === true){
return {'invalidPort':true};
} else if (vpnRemotePort < 1 || vpnRemotePort > 65000){
return {'invalidPort':true};
} else {
return null;
}
};
}
Use Example
VPNRemotePort: new FormControl('', [this.VpnRemotePortValidator])])
Component Html Use Example key name is invalidPort
<div *ngIf="VPNRemotePort.invalid && VPNRemotePort.dirty" class="text-danger padding-2">
<div *ngIf="VPNRemotePort.errors.invalidPort">
{{getVPNRemotePortInvalidErrorMsg}}
</div>
</div>
Custom Validation in Angular 6
Custom Validation function in Same Component Angular 6 and Angular 7
Custom Number Min Max Validation in Angular 6
No comments:
Post a Comment