Confirming the presence of values following hyphens in a string

Can you help me with this?

I want to create a function that checks if the string below (represented by var x) has values after each of the 7 dashes and returns valid or invalid

var x = 4-D-5240-P43-120-08A2-8123-0000 (valid)

Here are some examples where x is invalid:

var x = 4--5220--120-08C2-8072- (invalid)
var x = 4--5217-P41-120--8072- (invalid) 
var x = --5217-P41---8072- (invalid)

I attempted the following, but it fails when there is no value:

function test() {

var str1 = "4-D-5240-P43-120-08A2-8123-0000" //works
    str1 = str.split('-')

var str = "4--5240-P43--08A2-8123-0000" //error here <--
    str = str.split('-')

if (str.length < 8) { alert('validation failed') }
else { alert('validation passed!') }

}

Answer №1

Have you thought about using Regular Expressions (Regex)?

const
regexPattern = /(([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+)-([\d\w]+))/,

stringsToTest = ["4-D-5240-P43-120-08A2-8123-0000", "4--5217-P41-120--8072-", "--5217-P41---8072-", "4--5220--120-08C2-8072-"];

stringsToTest.forEach((str) => {

   console.log(`${str} is valid: ${ regexPattern.test(str) }`);

});

Answer №2

If you're looking to utilize regex for a similar task, take a look at this implementation.

   var pattern = /[0-9|a-z][-][0-9|a-z]/g;
   var sample1 = "4--5220--120-08C2-8072-";
   var sample2 = "4-D-5240-P43-120-08A2-8123-0000"


  if(sample1.match(pattern).length == 4) {
  alert("match");
  }
  else
  {
  alert("no match");
  }
  if(sample2.match(pattern).length == 4) {
  alert("match");
  }
  else
  {
  alert("no match");
  }

Answer №3

To start off, the first step is to declare the code and set the data-target to "-".

var id= "100-2-8-8-8-8-8ssss80-0";
var arr = id.split("-");

The next step involves checking if the code is valid or not. If there are less or more than 7 dashes, the output will be considered invalid. Otherwise, a function will run to verify if the dashes are in the correct positions.

function countDash(){
 if (arr.length ==8){
        result();
    }
    else{
        alert("invalid");
    }
}

Once we've split our function, it's important to check if every value in the array has a value assigned to it. If a dash is located at the beginning, end, or as multiple characters, an empty value will be returned.

function check(value){
return value.length<1;
}

We then utilize the previously declared function to examine each value within the array. If the array turns out empty, the output will be deemed invalid; otherwise, the code will be considered valid.

function result(){
    if(arr.some(check)){
        alert("invalid");
    }
    else{
        alert("valid");
    }
}

Lastly, we need to execute the initial function.

window.onload= countDash ;

I hope this explanation clarified the process for you. If there are any further steps to take, please feel free to inform me.

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

The most basic security measure for safeguarding a webpage

Currently, I am developing a website that requires customers to input a specific "code" in order to gain access. Upon visiting the site, users will be prompted to enter a simple code to proceed further. My programming skills are limited to HTML, CSS, and J ...

Tips for planning a successful outing using chart js

I created a graph using NextJs and ChartJs to display the COVID-19 statistics over the past 30 days. I retrieved this data from an API that provides information such as dates and stats: timeline: { cases: { '5/13/21': 5902343, '...&a ...

Minimizing switch-case statement into inactive input field (AngularJS)

While the code statement functions as intended, it may not be considered best practice due to the repetition of variables in each case of the switch statement. I am unsure of how to streamline the code or if there is an alternative to using a switch statem ...

Can you explain the functionality of the execCommand "insertBrOnReturn" feature?

I ran some code in Chrome and encountered an unexpected behavior: document.execCommand("insertBrOnReturn", false, true); http://jsfiddle.net/uVcd5/ Even though I've tried setting the last parameter to true or false, the outcome remains the same: ne ...

Reload the Angular application and navigate to a different state

Introduction In my extensive angular application, there are numerous forms for various items. These forms are associated with action objects that have unique schemaforms. The dropdowns in these forms vary based on the specific action and its parent comp ...

Generating numerous div elements with jQuery's zIndex property

While attempting to create a function that runs on the $(document).ready() event and is supposed to generate a new div, I encountered an issue. Whenever I try to create another div with the same DOM and Class attributes but in a different position, a probl ...

Tips on organizing a JSON object for a JavaScript project

For my project, I am designing a data structure that utilizes JSON. My goal is to create an efficient method for searching and editing the JSON object. Which structure would be considered standard in this scenario? Is there a preferred way to implement eit ...

What is the best way to properly redirect a page using a router link in Vue.js 2?

I've encountered an issue with the router-link component in Vue.js 2. I have set up my router file index.js import Vue from 'vue'; import VueRouter from 'vue-router'; import HomeView from '../views/HomeView.vue'; import ...

"Attempting to send JSON data via JsonResult is unsuccessful when trying to send a JSON object directly or using JSON

In my project, I have a class that looks like this: I've created a JsonResult method in the controller which takes an object of this class as a parameter: [HttpPost] public JsonResult NewAreaCode(AreaCode model) { return Json ...

Concealing axis lines within the initial circular grid or opting not to include them

Is there a way to incorporate some whitespace within the center circle of the radar chart? I'm aiming for the axis to commence at 1 radius (the initial circular line) or perhaps have the stoke set to 0 for the primary radius. Any assistance would be g ...

Is there a way to access a computed property within methods?

Currently, I am utilizing this particular package to implement infinite scrolling in Vue. In order to continuously add new elements during each scroll, I fetch JSON data from my API server and store it in a data object. Subsequently, I divide the array in ...

Using NgTable to sort and filter selections

I am working with two select elements. The first select is populated with names, and I would like the second select to only display the ages corresponding to the selected name. For example: If I select Jacob in the first select, I want the Age select to ...

Differentiate the items within a list containing identical divs using JavaScript

Currently, I am expanding my knowledge in HTML, CSS, and JS by incorporating Angular and JQuery. In one of my projects, there is a div labeled "eventBoxes" where multiple divs known as "eventBox" can be added. I have created a template for the eventBox i ...

EventListener fails to detect any changes in the dropdown menu

I am currently delving into the world of Django and JavaScript, but I am encountering an issue with the addEventListener function. It seems to be malfunctioning and I am at a loss. Can anyone provide insight into what may be causing this problem? Here is ...

Struggling with dynamic values and regex while utilizing HTML template strings. Need help overcoming regex challenge

Feeling stuck and seeking advice on improving regex usage. For a one-time substitution, the code below works for replacing a single element like -link-. var testHtmlStr = '<tr>' + '<td class="eve"><div class= ...

Router DOM in conjunction with Next.js

I am attempting to extract the output of the code in navigation, but unfortunately it is generating a dreadful error: Unhandled Runtime Error Error: You cannot render a <Router> inside another <Router>. You should never have more than one in ...

Unable to merge button-disable and code-behind functionality (JavaScript + code-behind)

After clicking on the Insert button, it performs its intended action. However, I want to prevent users from clicking the button multiple times by disabling it after it has been pressed. <asp:Button ID="Insert" runat="server" Text="Send" OnClick="Insert ...

Javascript - When I preview my file, it automatically deletes the input file

My form initially looked like this : <form action="assets/php/test.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /> ...

The file socket.io.js could not be located

I've encountered an issue with my node server where it is unable to serve the route /socket.io/socket.io.js as I consistently receive a 404 error. I have attempted compiling different versions of node (currently using 0.6.13 which works on another s ...

Problem Installing Express Sharp using Docker

When deploying via Docker, I encountered an error with sharp, even though it works fine on my workspace. I followed all the steps but still faced issues. Error: 'linux-x64' binaries cannot be used on the 'linuxmusl-x64' platform. P ...