Regular expression for validating passwords will be disregarded

I crafted this javascript and html code to validate the username and password input. Strangely, the regular expression for the password is not being acknowledged.

function checkDetails() {
  var uname = document.getElementById("uname").value;
  var pass = document.getElementById("pass").value;
  var reuname = /^[a-zA-Z]\w*$/;
  var repass = /^\w+{4,8}$/; // This line is causing issues
  if (reuname.test(uname)) alert(uname);
  else {
    alert("username should be alphanumeric and start with an alphabet");
    return false;
  }
  if (repass.test(pass)) alert(pass);
  else {
    alert("password should be alphanumeric with 4-8 characters");
    return false;
  }
}
body {
  background-color: teal;
}
#content {
  width: 550px;
  margin-left: auto;
  margin-right: auto;
}
h1 {
  text-align: center;
  margin-bottom: 30px;
}
#content table td {
  height: 30px;
}
<div id="content">
  <h1>Registration Form</h1>
  <form method="post" action="" onsubmit="return checkDetails(); return false;">
    <table>
      <tr>
        <td>Enter Username:</td>
        <td>
          <input type="text" name="uname" size="20" id="uname" />
        </td>
      </tr>
      <tr>
        <td>Enter Password:</td>
        <td>
          <input type="password" name="pass" size="20" id="pass" />
        </td>
      </tr>
      <tr>
        <td>Re-Enter Password:</td>
        <td>
          <input type="password" name="repass" size="20" id="repass" />
        </td>
      </tr>
      <tr>
        <td>Enter E-mail Address:</td>
        <td>
          <input type="text" name="email" id="email" />
          <td>
      </tr>
      <tr>
        <td>Re-Enter E-mail Address:</td>
        <td>
          <input type="text" name="reemail" id="reemail" />
          <td>
      </tr>
      <tr>
        <td>Enter Full Address:</td>
        <td>
          <textarea rows="10" cols="50" name="address" id="address"></textarea>
          <td>
      </tr>
      <tr>
        <td colspan="2" style="text-align: center;">
          <input type="submit" name="submit" value="submit" style="width: 100px; height: 30px;" />
        </td>
      </tr>
    </table>
  </form>
</div>

It works fine when I comment out that specific line.

/*var repass = /^\w+{4,8}$/;*/

Any idea why this strange behavior is happening?

Answer №1

Make sure to keep an eye on your console! You'll likely come across this message:

Uncaught SyntaxError: Invalid regular expression: /^\w+{4,8}$/: Nothing to repeat(…)

If you're unsure about what you were aiming for, consider giving this a shot instead /^(\w+){4,8}$/

Answer №2

function validateUser() {
  var username = document.getElementById("username").value;
  var password = document.getElementById("password").value;
  var patternUsername = /^[a-zA-Z]\w*$/;
  var patternPassword = /^\w{6,12}$/;
  
  if(patternUsername.test(username)) alert(username);
  else {
    alert("Username must start with a letter and be alphanumeric");
    return false;
  }

  if(patternPassword.test(password)) alert(password);
  else {
    alert("Password should be alphanumeric with a minimum of 6 characters and maximum of 12 characters");
    return false;
  }
  
  return true;
}
body{
  background-color: cyan;
}
#form-container{
  width: 550px;
  margin-left: auto;
  margin-right: auto;
}
h1 {
  text-align: center;
  margin-bottom: 30px;
}
#form-container table td{
  height: 30px;
}
<div id="form-container">
  <h1>User Registration Form</h1>
  <form method="post" action="" onsubmit="return validateUser();">
    <table>
      <tr>
        <td>Enter Username:</td>
        <td>
          <input type="text" name="username" size="20"
          id="username" />
        </td>
      </tr>
      <tr>
        <td>Enter Password:</td>
        <td>
          <input type="password" name="password" size="20"
          id="password" />
        </td>
      </tr>
      <tr>
        <td colspan="2" style="text-align: center;">
          <input type="submit" name="submit" value="Submit"
          style="width: 100px; height: 30px;"
          />
        </td>
      </tr>
    </table>
  </form>
</div>

I've updated the regex for the password validation in the code. Feel free to test it out.

Answer №3

To make your regular expression valid, remove the '+' sign.

var passwordPattern = /^\w{4,8}$/;

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

Tips for integrating JavaScript into a Django project

I am currently developing a Django application that I want to make highly flexible and reusable. As I work on this project, I find myself thinking about the best practices for ensuring that my app can seamlessly integrate into larger projects where jQuer ...

Troubleshooting issue with Ajax delete functionality in Laravel 5.2

I've encountered an issue while attempting to remove a record from my mysql database within a laravel application. The error message I'm receiving is TokenMismatchException, and I'm unsure of the cause. Any assistance would be greatly apprec ...

Steps for displaying a loading gif animation prior to retrieving text content using JavaScript

Before fetching the PHP result, I want a loading GIF image to display within the div section. <!DOCTYPE html> <html> <head> <title> CTR Calculator Tool | Free Click Through Rate Online Calculator </title> & ...

Tips on removing either the date or time when input type date and input type time share the same ng-model

In my Ionic app built with AngularJS, I have a form where the date and time are displayed separately but share the same data-ng-model: <input type="date" id ="actualVisitDate" data-ng-model="actualVisitDate" required> <input type="time" id ="actu ...

Provide a TypeScript interface that dynamically adjusts according to the inputs of the function

Here is a TypeScript interface that I am working with: interface MyInterface { property1?: string; property2?: string; }; type InterfaceKey = keyof MyInterface; The following code snippet demonstrates how an object is created based on the MyInter ...

Tips for creating a nodeCategoryProperty function for a TypeScript Model:

nodeCategoryProperty function has a signature requirement of (a: ObjectData, b?: string) => string. In my opinion, this should be updated to (a: ObjectData, b?: string) => string | void, as the function is intended to not return anything if used as a ...

Switch between various 3D models in three.js by utilizing dat.gui interface

I'm currently attempting to switch between multiple 3D models (loaded with OBJMTLLoader.js) that are rendered in my three.js scene. Using dat.gui, I've created a dropdown list of model names where selecting one will add the corresponding obj mode ...

Harnessing the Power of JSON in Rails to Enhance Your jQuery UI Autocomplete Form

In the context of a rails application, I have been exploring different methods to fetch data from a JSON file. Despite my efforts, I have not been able to find a solution that suits my requirements. The static data I have is quite extensive, consisting of ...

The slider customization on Joomla is functioning perfectly on my local machine, but it seems to be encountering some issues on

Having recently started working on a Joomla website for the first time, I encountered some challenges when trying to add a slider module. Despite successfully implementing the slider on my local machine, I faced issues when transferring the code to the liv ...

Automated inclusion of <a> tags for headers implemented in Pandoc

This specific Markdown syntax: # Starting Point Gets transformed into this exact HTML code once processed with Pandoc: <h1 id="starting-point"><a href="#starting-point">Starting Point</a></h1> The technique I follow for using Ma ...

Creating a Navigation Bar with a Dropdown Menu in HTML

Apologies if this question has been asked before, but I've searched everywhere and can't find an answer. All my searches just bring up dropdown menus with <nav></nav> Consider this table (serving as a navigation bar): <table cl ...

Enhance the appearance of the standard black rectangle displaying the messages "No video source" or "No video permissions"

Is there a way to change the styling of the video element that appears as a black rectangle with a strikethrough play button when the user is prompted for permission on Safari? Does it have a specific ID, class, or tag that can be targeted? I'm curre ...

Invoke the jQuery document.ready function within a separate jQuery or JavaScript function

Encountering a difficult issue: Attempting to invoke the document.ready() function inside another JavaScript function, but upon doing so, an error message stating "function is not defined" appears. Below is the provided code: This first function serves as ...

The mobile homepage is experiencing issues with its two scrollbars - one large and one small - they do not seem to

The issue I am facing is not easily reproducible as I have a large amount of code to sift through and pinpoint the exact problem. My hope is to receive suggestions or insights into what might be causing the problem so that I can further troubleshoot from ...

What is the best way to initiate a saga for an API request while another call is currently in progress?

During the execution of the first action in saga, the second action is also being called. While I receive the response from the first action, I am not getting a response from the second one. this.props.actions.FetchRequest(payload1) this.props.actions.F ...

After AJAX has been loaded, Readmore.js fails to function properly

I am currently struggling to get the Readmore.js plugin working with AJAX content. The code snippet I have included is not cutting off the content inside the .more element as expected. <td><div class="more"><?php echo $row['book_desc&a ...

Changing the background color of a PHP input based on the webpage being viewed - here's how!

I'm in the process of creating a website where each page will have its own unique background color. Additionally, I am using a PHP input for both the header and footer sections, which need to change their background colors based on the specific webpa ...

Incorporate a section of text to flow around a floated image within a paragraph

https://i.sstatic.net/s5aFq.png How can I achieve the text wrapping above an image similar to the layout in the sunflower picture? I have tried using relative positioning and adjusting the top property, but it doesn't allow the text to wrap around th ...

Modifying the content of a paragraph by incorporating information from various sources

I need a way to input measurements for my items in text fields, and then with the click of a button, transfer those measurements into a paragraph in corresponding fields. The code I am currently using is shown below: <!DOCTYPE html> <html> & ...

Please enter data into the input fields provided in the text

Below is the code where Google transliteration is used for typing in Indian language in a text field. There are two routes with different page IDs. Initially, the transliteration works fine on the default page. However, when changing routes, an error occur ...