-1

What could i use in a regexp variable to ensure a field contains only nummbers but also allows a full stop (period) and various money symbols (£,$)

Hope you can help!

Thanks

Here is what i have so far:

var validRegExp = /^[0-9]$/;

1 Answers1

1

I would probably go with the following:

/^\d+(\.[\d]+){0,1}[€$]{0,1}$/gm

It matches at least one digit, then allows you to put zero or one period somewhere in there and then needs at least one digit after the period. At the end of it you may put one of the currency symbols explicitly named. You have to add all of the ones you want to support though.

Let try it for the following list:

3.50€
2$
.5
34.4.5
2$€

afasf

You will see that only the first two are matched correctly. Your final output are the ones in group 0.

const regex = /^\d+(\.[\d]+){0,1}[€$]{0,1}$/gm;
const str = `3.50€
2\$
.5
34.4.5
2\$€

afasf
`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
Ruben Bohnet
  • 392
  • 1
  • 12
  • Hi it didn't quite work... It isn't registering the fact that $ is allowed – Maymun Hashim-Subhan Jun 13 '18 at 12:57
  • Here is my full script: `function onChange(control, oldValue, newValue, isLoading, isTemplate) { if (!isLoading && newValue !='') { var inbox = g_form.getValue('agreed_cost'); //The following ensures the (email address) has valid and required characters. //^ and $ mark Start and End of the input string to match with this RegEx var validRegExp = /^\d+(\.[\d]+){0,1}[€$]{0,1}$/gm; g_form.hideFieldMsg('agreed_cost'); if (inbox.search(validRegExp) == -1){ alert ('Agreed cost is invalid'); g_form.clearValue('agreed_cost'); } }} ` – Maymun Hashim-Subhan Jun 13 '18 at 12:57
  • @MaymunHashim-Subhan The regex seems to be filtering out "2$" just fine when I tried it. Can you tell me the exact string that isn't matched correctly? – Ruben Bohnet Jun 13 '18 at 13:05
  • Ah sorry I was putting the money symbol at the front when testing, i'll change the order in the code, thanks!! – Maymun Hashim-Subhan Jun 13 '18 at 13:06
  • @MaymunHashim-Subhan If you prefer to have the currency sign at the beginning you could use this regex: `^[€$]{0,1}\d+(\.[\d]+){0,1}$` – Ruben Bohnet Jun 13 '18 at 13:09