Validation of forms - Must include one particular word from a given set

I am in the process of utilizing Javascript to validate an input field with the specific formatting requirements outlined below:

  • "WORD1,WORD2"

The input must contain a comma separating two words, without any spaces. The first word (WORD1) can be any word, but the second word (WORD2) has to be one of the following options:

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

If the input does not contain any of the designated words for WORD2, the validation will fail. For instance: "ASDA,USD" would pass validation, while "ASDA,ASD" would not.

How should I proceed with coding this? Here's what I've developed so far for uppercasing 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 class="col-auto">

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

<div class="col-auto">
<button id="inputTextBtn4" class="btn set-btn" onclick="cryptoValidate()">Add</button>
</div>
                  
<p id="demo2" style="display: none"></p>

Answer №1

Opt for a Selection

(code adapted to accommodate any text prefix)

Selections are commonly utilized to restrict choices to a specified set of values, reducing the unnecessary intricacy of parsing and validating user input. Thus, in this resolution, "word2" has been transformed into a <select> featuring currency abbreviations.

The text prefix, referred to as "word1", is an input element with a pattern attribute set. This pattern permits 1-5 letters without spaces, although it can be adjusted as needed. User input undergoes validation through code utilizing the checkValidity method before being converted to uppercase.

Following successful validation, the code generates a string that combines: 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);

    // take necessary action
  }
  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>

Answer №2

Instead of relying on complex JavaScript functions, opt for basic level regular expressions.

Regular expressions are great for string matching and validation purposes.

Let me break down the regular expression I came up with:

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

() is used for grouping, [a-zA-Z] matches any alphabet (uppercase or lowercase), + means one or more occurrences, | indicates alternatives.

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("👍");
} else {
    console.log("👎");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I require adding a new line of information into the database table

I am looking for help with adding data into a table without any user inputs. Specifically, I want to add data by passing them into an array and then be able to call them at the "Add Site" button so that the row is added into the table. Can someone assist m ...

Developing a personalized Django widget featuring hints for "suggestions" derived from the validation process

I currently have a simple model setup: class MyModel(models.Model): my_field = models.CharField() Additionally, I have created a basic form for this model: class MyFrom(forms.ModelForm): class Meta: model = MyModel Furthermore, I have i ...

Modifying an @Input element within a component does not result in any changes being reflected in the parent component

Here is the scenario with my component: @Component({ selector: 'child' }) export class ChildComponent { @Input() childObject: ChildObject; changeObject(newObject: ChildObject){ childObject = newObject; } } After calling ...

Adding a CSS style to specific sections of a string that is quoted in a Razor ASP.NET file

Is it possible to format a specific part of a string? I'm trying to only stylize the word within quotation marks. This is my cshtml code: { <div class="h-44 overflow-auto text-left mx-4 mb-4"> <p ...

Using multiple instances of the jQuery datepicker within a datalist

I have successfully implemented the jQuery date picker, but I am encountering an issue where it only works on the first textbox within the datalist. I am struggling to extend the functionality of the datepicker to work on all textboxes within the datalist. ...

Looking for a way to detect changes in a select menu using Angular?

How can I determine with the openedChange event if there have been any changes to the select box items when the mat select panel is closed or opened? Currently, I am only able to detect if the panel is open or closed. I would like to be able to detect any ...

The transitioning period caused the gooey effect to become distorted

I'm currently working on creating a radio button with a gooey effect. The transition looks great, but once it's complete, the colors don't blend well and the edges glow in an odd way. I've been searching for the root of the issue, but ...

Customize the Grid Offset in CSS like BootstrapCSS Grid Offset

I am attempting to replicate the offset feature in Bootstrap's desktop grid system, where a class like .col-md-offset-3 creates an offset using margin-left. However, in my implementation found at this link, the CSS selector does not work as intended: ...

Synchronizing the call of various views in an Angular application

I'm currently working on an angular single page application with a specific structure in mind. "app.parent - main parent state" "app.parent.childState - child state" "app.parent.childSatate" includes 4 different named views. My goal is to display so ...

Issue with jqGrid Multiple Selection

When constructing my jqgrid, I utilize the following code: multiselect: true This enables a check all column. However, clicking the check all checkbox (located at the header) selects all checkboxes, but does not click the checkboxes in each row. You can ...

The imported package is not functioning properly within the project

I've recently developed a Typescript Package and I want to test it in an application before publishing it on NPM. The main file (index.ts) of the package is structured like this => import Builder from './core/builder'; export default ...

Tips for accessing basic information from these websites without encountering CORS issues

Having issues retrieving data from the following two sites: and Eurolottery. The CORS issue is causing the problem, and I was able to retrieve data using a Chrome CORS extension and the provided code below: var HttpClient = function() { this.get = fu ...

Tap here to switch between 2 jquery functions

Due to the deprecation of the toggle() method in jQuery version 1.8 and its removal in version 1.9, an alternative approach is needed for versions 1.11 and above. You can check out the documentation for more information. If you are looking to replicate th ...

Array's Javascript length of 0

I have encountered some strange behavior with the following code. It's displaying an array length of 0 even though I can see a length greater than 0 when printing it right before that: var getTopSelection = function(callback) { var topSelection = ...

What is the best way to eliminate excess space on the right side in Bootstrap 4 while in mobile view?

I'm struggling to understand why this layout is not responsive on mobile devices, triggering a bottom scroll bar at around 616px. I'm looking for a solution to hide the scroll bar at least until 414px for iPhones and other smartphones. I've ...

Guide on assigning JSON response values to TypeScript variables in Angular 4

I'm just starting with Angular 4 and I'm attempting to retrieve a JSON value using http.post. The response I'm receiving is: {"status":"SUCCESS"} component onSubmit(value: any) { console.log("POST"); let url = `${this.posts_Url}`; t ...

Start up JQuery User Interface

I've been having some trouble with Jquery UI and it's been quite frustrating. To try to understand better, I have created a simple test case which you can view here: http://jsfiddle.net/vmZap/ Essentially, I have included JQUERY, JQUERY-UI, and ...

Can you provide guidance on how to showcase the chat date and time for each message in a webchat created with the bot framework SDKV4 using C#

I've successfully created a chatBot using bot framework SDKV4 in C# with the WebChannel as the channel. Everything is functioning properly, but I have a specific goal in mind: For each message that the user types or the Bot replies to, I want a time ...

Resolve the issue of Dojo images not appearing on a div in Internet Explorer

I am trying to incorporate images into a dojo chart using the given code: var l_images = ["images/clearnight.png","images/clear.png","images/partlyCloudy.png","images/cloudy.png","images/showers.png","images/rain.png","images/thunderstorms.png","images/ic ...

navigating up and down html elements using css selectors

Within my code, I have this odd repetitive HTML structure (with no classes) and I'm looking to extract all links along with the accompanying text below each link. While it's simple enough to grab all the links using a basic CSS query selector li ...