import { ValidationErrors , Validator } from '@angular/forms' ; import { TranslateService } from '@ngx-translate/core' ; import { CustomFormControl } from 'app/controls/click-to-edit/click-to-edit.component' ; import { PortalResources } from 'app/shared/models/portal-resources' ; export class DecimalRangeValidator implements Validator { static leftRegExp : RegExp = /^[0-9]+(\.[0-9]*)?$/ ; static rightRegExp : RegExp = /^[0-9]*(\.[0-9]+)?$/ ; private _rangeMin : number ; private _rangeMax : number ; private _formatErrorMessage : string ; private _rangeErrorMessage : string ; constructor ( translateService , rangeMin = 0.0 , rangeMax = 100.0 ) { this . _rangeMin = rangeMin ; this . _rangeMax = rangeMax ; this . _formatErrorMessage = translateService . instant ( PortalResources . validation_decimalFormatError ) ; this . _rangeErrorMessage = translateService . instant ( PortalResources . validation_decimalRangeValueError , { min : this . _rangeMin , max : this . _rangeMax , } ) ; } validate ( control ) { if ( control . dirty || control . _msRunValidation ) { const stringValue = control . value ? control . value . toString ( ) : '0' ; const trimmedValue = stringValue . charAt ( 0 ) === '-' ? stringValue . substring ( 1 ) : stringValue ; if ( ! trimmedValue || ( ! DecimalRangeValidator . leftRegExp . test ( trimmedValue ) && ! DecimalRangeValidator . rightRegExp . test ( trimmedValue ) ) ) { return { invalidDecimalError : this . _formatErrorMessage } ; } const decimalValue = Number . parseFloat ( stringValue ) ; if ( decimalValue < this . _rangeMin || decimalValue > this . _rangeMax ) { return { outOfRangeError : this . _rangeErrorMessage } ; } } return null ; } }