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

AJAX Form Submission for CommentingAJAX allows for seamless form submission

Currently facing an issue with a form submission that is not displaying comments without refreshing the page. When the submit button is clicked, it redirects to the top of the page without executing any actions - no insertion into the database and subseque ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

Guide on integrating buefy (a vue.js component library) into your Laravel blade template

I'm currently integrating buefy into my project, but I'm encountering issues with using vue.js on Laravel 5.8. Can anyone offer assistance? Here is the code snippet from my app.js: require('./bootstrap'); window.Vue = require('v ...

"Executing the command 'npm run dev' is successful, however, the command 'next dev' does not yield the expected result

Trying out Next for the first time using npx create-next-app, but running into issues with the scripts. While npm run dev works without any problems, executing next dev gives me an error saying zsh: command not found: next. Any idea why this is happening? ...

jQuery triggers change event twice when radio group is manually modified

After selecting "A&L" in the dropdown menu, the radio group is hidden and its value is changed to "n". I attempted to trigger the change event to make the "Hello" message disappear as well, but it seems to be executing twice - once correctly and then ...

What is the best library to utilize for uploading an Excel file in a React application?

As a beginner in JS and React, I have a simple question that I hope someone can help me with! I am trying to figure out how to upload an excel file using a form and then extract the data from the rows and columns. For example, I would like to calculate th ...

Executing VueJS keyup handler after the previous onclick handler has been executed

Link to example code demonstrating the issue https://codepen.io/user123/pen/example-demo I am currently facing an issue with a text field named search_val that has a watcher attached to it. The text field includes a v-on keyup attribute to detect when th ...

The AngularJS HTTP interceptor is a crucial component for handling

Is there a way to use an interceptor in AngularJS to log "finished AJAX request" when any request is completed? I've been exploring interceptors and currently have the following setup, but it triggers at the beginning of the request rather than the e ...

Set a default value for a FormControl within react-bootstrap

When working with my email address, I utilized the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="44362125273069262b2b30373036253404746a76706a71">[email protected]</a>. In order to specify the initial value chosen ...

Employing parseFloat() and parseInt() functions together with regular expressions in JavaScript for converting a Comma Separated Values (CSV

I've been working on converting a CSV file to a local 2D array and I'm curious if there's a more efficient method of changing strings to floats/int rather than relying on regex paired with parseFloat() / parseInt. Any bright ideas or sugges ...

Utilize Javascript to Populate Form Fields Based on "Selected Name"

I am currently facing a challenge in using javascript to automatically populate a form, specifically when it comes to setting the value for the country field. <form action="/payment" method="post" novalidate=""> <div class="input_group"> ...

Determine if offcanvas element is visible upon initialization in Bootstrap 5 Offcanvas

I have a search-filter offcanvas div for location and property type on this webpage: On larger screens (desktop), the offcanvas is always visible, but on smaller screens (mobile), it is hidden and can be toggled with a button. This functionality works per ...

Bringing back a Mongoose Aggregate Method to be Utilized in Angular

I'm having trouble returning an aggregate function to Angular and encountering errors along the way. I would really appreciate some assistance with identifying the mistake I am making. The specific error message I receive is Cannot read property &apos ...

Integrate retrieved JSON data using Ajax into D3 visualizations

Could someone please guide me on how to incorporate fetched JSON data using Ajax into D3? I've integrated this example here into my project and now I just want to populate the radial layout with my own data. The image below shows the current bilevel r ...

"Exploring the world of custom middleware in NextJs on a localhost

Question regarding nextjs page middleware: the documentation states that the request object should include geo, IP, ua, cookies, and nexturl properties. Visit the link for more information. I am attempting to retrieve the user's location using page m ...

Which one should I prioritize learning first - AngularJS or Laravel?

As a novice web developer, I am embarking on my first journey into the world of frameworks. After much consideration, I have narrowed it down to two options: AngularJS and Laravel. Can you offer any advice on which one would be best for me to start with? ...

After refreshing the page, the console log within the React useEffect function ceases to function

Incorporating the 'useEffect' function to fetch data and store it in the 'ratings' array has proven successful. However, there seems to be an issue when attempting to iterate through the elements of the 'ratings' array for log ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

The way in which notifications for updates are displayed on the Stack Overflow website

Could someone shed some light on how the real-time update messages on this platform are created? For instance, when I am composing a response to a question and a new answer is added, I receive a notification message at the top of the page. How is this fun ...

What is the best way to retrieve data from the state in react components?

After fetching data from my API using a getAll call, I stored all the values in this.state. However, I am struggling with extracting the arrays or objects from my state. Specifically, I am interested in retrieving the 'id' field from: 0: {id: 1, ...