Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading