Home > other >  Form validation - Must contain a specific word from a list
Form validation - Must contain a specific word from a list

Time:05-11

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

function cryptoValidate() {

var cryptoBaseCurrencies = ("USD", "AUD", "BTC", "CAD", "CHF", "EUR", "GBP", "ETH", "JPY", "NZD");

  let x = document.getElementById("inputText4").value;
  let text;
    if (x.toUpperCase() != x) {
      document.getElementById('demo2').style.display = "block";
      text = "Crypto and base must be uppercase";
      document.getElementById("inputText4").value = '';
    }
        else if WORD FORMATTING HERE {
        document.getElementById('demo2').style.display = "block";  
        text = "Missing the correct base currency"
        document.getElementById("inputText4").value = '';
        }
        else {
          text = "Input OK";
          document.getElementById('demo2').style.display = "none";
        }
          document.getElementById("demo2").innerHTML = text;
}

HTML

<div >

<input type="text" id="inputText4"  aria-describedby="TextHelpInline" placeholder="e.g. BTC,USD"/>
</div>

<div >
<button id="inputTextBtn4"  onclick="cryptoValidate()">Add</button>
</div>
                  
<p id="demo2" style="display: none"></p>

CodePudding user response:

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

rate.addEventListener("change", e => {

  let el = rate.querySelector("input");

  if (el.checkValidity()) {

    let word1 = el.value.toUpperCase();
    let word2 = rate.querySelector("option:checked").value;

    console.log("You selected: ", word1   ","   word2);

    // do something
  }
  else {
     console.log("Invalid input");
  }

});
body {
  font-family: sans-serif;
  padding: 1em;
}

#rate input:invalid ~ span:after {
  content: "Please enter 1-5 characters without spaces";
  color: red;
  display: block;
  font-size: 0.8rem;
}
<span id="rate">
  <input type="text" pattern="[A-Za-z]{1,5}" spellcheck=false placeholder="enter prefix">
  <select>
    <option>USD</option>
    <option>AUD</option>
    <option>BTC</option>
    <option>CAD</option>
    <option>CHF</option>
    <option>EUR</option>
    <option selected>GBP</option>
    <option>ETH</option>
    <option>JPY</option>
    <option>NZD</option>
  </select>
  <span></span>
</span>

CodePudding user response:

Rather than using javascript at very high level; Use regular expressions at basic level.

Regular expression is used to match strings and validation.

let me explain the regular expression that I created

let regex = /([a-zA-Z] ),(USD|AUD|BTC|CAD|CHF|EUR|GBP|ETH|JPY|NZD|)$/;

() represents grouping [a-zA-Z] reprents any alphabet (caps or small) represents more than one | represents alternative

let regex = /([a-zA-Z] ),(USD|AUD|BTC|CAD|CHF|EUR|GBP|ETH|JPY|NZD|)$/;
let str = "Iamanexamplestring,BTC"; //
let result = regex.test(str);

if(result) {
    console.log("           
  • Related