angularvalidationinputcurrency

How to validate a currency field on input event using .replace angular reactive forms


I am trying to validate a currency input field which allows only numeric values and dot(.) dot is allowed but not as a first character. I came up with the below pattern, everything works fine except one scenario, where . is getting validated to true even if its first character.

validateInput(event) {
event.target.value = event.target.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/(\.\d{2}).+/g, '$1')) 

}

How can i correct this so that . is not allowed as first character? Any help on this is much appreciated, TIA.


Solution

  • We can use the regex /^\.$/g validate the scenario for . and set it to blank, thus fixing the problem.

      validateInput(event: any) {
        event.target.value =event.target.value
                .replace(/[^0-9.]/g, '')
                // to handle dot scenario
                .replace(/^\.$/g, '')
                .replace(/(\..*?)\..*/g, '$1')
                .replace(/(\.\d{2}).+/g, '$1');
      }
    

    Stackblitz Demo