Kode_12 Kode_12 - 15 days ago 5
Javascript Question

How can I find one instance of a character using REGEX?

I have an input field that should only accept characters used in a currency syntax (dollar sign, numbers, commas, and decimals). How can I write my REGEX to check if a string contains atleast one character that is NOT from the above listed characters?

I've tried the following, but the problem with this expression is that if one valid character is present in the string it throws the 'else' statement. (unitPriceVal is the user input string)

I want to write a regex that checks if the WHOLE string consists of the valid Currency, if true run the else statement

validCurrency = /([0-9\$.,])/;

if (!unitPriceVal.match(validCurrency) || unitPriceVal == "") {
unitPrice.setValueState("Error");
} else {
unitPrice.setValueState("None");
}
},

Answer

I want to write a regex that checks if the WHOLE string consists of the valid Currency

To check the whole string, anchor the match to the beginning and end of the input, using ^ and $, and make sure what's in between is a sequence (+) of allowable characters:

/^[\d$.,]+$/;

You don't need parentheses. You also don't need to escape the $ inside the character set. Finally, you can use \d for a digit.

Often, it's better to use the input element's pattern attribute to do this check. In that case, you don't need the anchors (they're implied):

<input pattern="[\d$.,]+">
Comments