Skip to content
Advertisement

Form validation – Must contain a specific word from a list

I’m trying to use Javascript to validate an input field to have the specific formatting below:

  • “WORD1,WORD2”

So there has to be a comma in between two words, no spaces. WORD1 can be any word, but WORD2 has to be a word from the following list:

  • “USD”, “AUD”, “BTC”, “CAD”, “CHF”, “EUR”, “GBP”, “ETH”, “JPY”, “NZD”

If the input field doesn’t have any of the words in WORD2, then the validation will fail. For example: “ASDA,USD” would be considered valid and have no problems. However, “ASDA,ASD” would be considered invalid.

How can I go about programming this? Here’s what I have so far for uppercase validation.

Javascript

JavaScript

HTML

JavaScript

Advertisement

Answer

Use a Select

(code revised to allow any text prefix)

Selects are typically used to limit options to a defined set of values. This avoids the needless complexity of parsing and validating user input. So in this solution “word2” has been made a <select> with a list of currency abbreviations.

The text prefix, or “word1”, is an input with a pattern attribute. The pattern allows 1-5 letters without spaces, but this could be modified as required. User input is validated by code using checkValidity and then converted to upper case.

Once validated, the code returns a string of: word1,word2

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement