JavaScript, detecting repeated characters

I need to create a script that checks an input box (password) for the occurrence of the same character appearing twice. This script should work alongside existing regex validation. I believe I will need to use a loop to check if any character appears twice, but I am unsure about the conditions for this function. If anyone has suggestions on how to accomplish this, it would be greatly appreciated. For example: "ABad12" should pass, while "AbAc12" should return false. Thank you in advance.

function checkForm(form)


{

 var re = /^\w{6,10}$/;

  if(!re.test(form.pwd1.value)) {
  alert("Error: Password must be between 6-10 characters!");
  form.inputfield.focus();
  return false;
  }


}

Above is an example of the script I want to combine with additional regex validations.

Answer №1

If I were to tackle this task, here's how I'd go about it:

let testString = "ABad12",
    isValid = testString.split("").filter(function(char, index, array) {
        return array.indexOf(char) !== index;
    }).length === 0;

if (!isValid) {
    // ...
}

It's worth noting that the filter() method may not be supported in older browsers, so be sure to check the browser compatibility page beforehand.

Answer №2

Forget about using a for loop, all you need is a basic regex pattern:

(\w)\1+

var checkRegex=/(\w)\1+/;
checkRegex.test("aa") -> will result in true;
checkRegex.test("ab") -> will result in false;

Answer №3

Here is a straightforward piece of code written in pure JavaScript, without using regular expressions:

function checkForDuplicates(s) {
  var index;
  for(index = 0; index < s.length - 1; index++) {
    if(s.indexOf(s.substring(index, index + 1), index + 1) >= 0) {
      return false;
    }
  }
  return true;
}

This function scans the string sequentially and verifies if any character is repeated later within the string.

Incorporating this code into your project can enable you to provide customized error messages. Instead of simply returning false, consider calling an error handling function to display a specific message such as

'Error: character “' + s.charAt(index) + '” appears more than once.'

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

Revamping the settings page by featuring a single "save changes" button

Is it possible to create a settings.php page where users can update their personal information, such as username, password, and email, all within the same page? I know how to perform these tasks individually, but I'm unsure about integrating different ...

The cannon-es program experiences crashes every time two Convex polyhedrons collide with each other

Currently, I'm working on implementing a dice roller using three.js and cannon-es. Everything runs smoothly when there's only one dice, rolling against the ground plane in a satisfactory manner. However, the trouble arises when I add a second di ...

What is the reason behind fullstack-angular generator utilizing Lo-Dash's merge rather than document.set?

This is the original code snippet used for updating: exports.update = function(req, res) { if(req.body._id) { delete req.body._id; } Thing.findById(req.params.id, function (err, thing) { if (err) { return handleError(res, err); } if(!thing) { ...

Update the image and heading simultaneously when hovering over the parent div

I am looking to enhance the user experience on my website by changing the color of headings and images when a user hovers over a specific section. Currently, I have been able to achieve this effect individually for each element but not simultaneously. Any ...

Retrieve the information transmitted to an EJS file within a separately included JavaScript file

I'm currently utilizing express js to render a file by using: res.render('plain',{state:'admin'}) The file plain.ejs includes main.js: <script src ="/main.js"></script> I need assistance on how to access the state v ...

Learn the technique of looping through multiple HTML elements and wrapping them in Vue.js easily!

i need to wrap 2 HTML elements together Here is my code snippet using Vue.js <tr> <th v-for="(item9,index) in product_all" :key="item9.id"><center>Qty</center></th> <th v-for="(item99,index) in product_all" :key=" ...

Utilizing jQuery to update dropdown selection based on JSON object values

In my JSON value, I have the following roles: var roles = { "roles":[ {"role_id":2,"role_name":"admin"}, {"role_id":4,"role_name":"QA"}, {"role_id":3,"role_name":"TL"}, {"role_id":5,"role_name":"user"}, {"role_id":1,"role_name":"r ...

Retrieving values using the jQuery .each() function and passing them to an AJAX request

Is it possible to set jQuery AJAX outside of .each in the script provided below? $('#btnUpdate').click(function() { $('#result').html(''); $('.moduleIDInput').each(function() { var uid = $(this). ...

Include a new button in the react material-table toolbar

I am looking to enhance the material-table toolbar by adding a new button. This button will not be directly related to the table, but instead, it will open a modal window with additional information. The button I want to add is called "quotations" and I w ...

Having difficulty generating dynamic rows and tree dropdowns in AngularJS

Struggling to implement dynamic row functionality with Angular JS. The rows are working well, but I also need to incorporate a tree dropdown within each row. Unfortunately, clicking the "add row" button populates the same data in all rows. I have shared m ...

Unlock real-time alerts with the power of JavaScript and PHP!

I am currently working on enhancing my skills in javascript. I have a basic idea of what I want to achieve. My goal is to create an automated javascript function that accesses a php page. This php page will create an array of new notifications for the ja ...

Do we need to handle promise resolution after sending a response to the client?

After sending the response to the client, I have a requirement to execute an asynchronous function. res.json({}); someAsyncFunction(); //this function does not require await Is it considered problematic to call this function without awaiting its promise? ...

Incorporate the previous page's location path into the next page using Props in Gatsby Link

My website has multiple pages with paginated lists of blog posts, each post generated from markdown using createPage(). Each page in the /posts directory displays 3 post previews and subsequent pages are numbered (e.g. /posts/2). I am trying to pass the p ...

Retrieve the image description using the file_picker_callback and image uploader in Tinymce

TL:DR I am attempting to retrieve the value of the image_description field using JavaScript to include it in my post XHR request Original query: I am utilizing the file_picker_callback type image I have enabled the image_description input field in my ...

JavaScript personalized video controls. Silence the video by manipulating the input range element

As a newcomer to javascript, I am working on creating custom video controls using js. One issue I am facing is with a span element that contains a mute/unmute icon. When I hover over this span element, a child element appears with an input range bar for ad ...

What is the best approach to configure Nuxt.js to recognize both `/` and `/index.html` URLs?

Currently, I have set up my Nuxt.js in default mode with universal and history router configurations. After running nuxt generate, the generated website includes an index.html file in the dist folder. This means that when the website is published, it can ...

Error message: "Uncaught ReferenceError: $ is not defined in BackboneJS and RequireJS"

In my Backbone application, I am using RequireJS. However, I keep encountering the error message Uncaught ReferenceError: $ is not defined, indicating that my libraries may not be loading properly. This is what my RequireJS config looks like: require.con ...

Absolute positioning causes an element's height to increase

As I delve into the realm of typographical animations and seek to calculate the baseline of a font at various sizes, I've stumbled upon a peculiar discovery: It appears that the height values of elements tend to increase in an erratic manner when thei ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Discovering the art of importing JavaScript files dynamically within controllers

I have one main form through which I pass data from 10 different components, each including the ID of a table that I need to retrieve data from in the database. The issue I am facing is that the code responsible for fetching this data asynchronously is spr ...