JavaScript validation is failing to return false when re-entering the password

My JavaScript validation code is working fine.

Javascript: All fields return false when re-entering the password, but JavaScript does not return false if it's not working

The Re-Enter password JavaScript code is failing to work...

An alert is displayed ... after the alert is shown, the form gets submitted and return false doesn't work as expected...

[Here is js Fiddle][1]


  [1]: https://jsfiddle.net/Ln1cmaps/

**HTML**

    <div class="container">
                <div class="row main">
                    <div class="main-login main-center">
                    <h2>Admin Registration</h2>
                        <form class="" method="post" action="" name="signup" onsubmit="return validate()">

                            <div class="form-group">
                                <label for="name" class="cols-sm-2 control-label">Your Name</label>
                                <div class="cols-sm-10">
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
                                        <input type="text" class="form-control" name="name" id="name"  placeholder="Enter your Name"/>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="email" class="cols-sm-2 control-label">Your Email</label>
                                <div class="cols-sm-10">
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-envelope fa" aria-hidden="true"></i></span>
                                        <input type="email" class="form-control" name="email" id="email"  placeholder="Enter your Email"/>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="username" class="cols-sm-2 control-label">Username</label>
                                <div class="cols-sm-10">
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-users fa" aria-hidden="true"></i></span>
                                        <input type="text" class="form-control" name="username" id="username"  placeholder="Enter your Username"/>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="password" class="cols-sm-2 control-label">Password</label>
                                <div class="cols-sm-10">
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
                                        <input type="password" class="form-control" name="password" id="password"  placeholder="Enter your Password"/>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="confirm" class="cols-sm-2 control-label">Confirm Password</label>
                                <div class="cols-sm-10">
                                    <div class="input-group">
                                        <span class="input-group-addon"><i class="fa fa-lock fa-lg" aria-hidden="true"></i></span>
                                        <input type="password" class="form-control" name="confirmpassword" id="confirm"  placeholder="Confirm your Password"/>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group ">
                                <input type="submit" name="submit" value="Register" class="btn btn-primary btn-lg btn-block login-button" /> 
                            </div>  

                        </form>

                </div>
            </div>
            </div>


**Javascript Validation Code**

    function validate() {
            var name = document.signup.name.value.length;
            var email = document.signup.email.value.length;
            var username = document.signup.username.value.length;
            var password = document.signup.password.value;
            var rpass = document.signup.confirmpassword.value;
            var re =(/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,16}$/);

            if(name=="") {
                alert("Please Enter Your Name");
                document.signup.name.focus();
                return false;
            }

            if(name<3) {
                alert("Please Enter Your Correct Name");
                document.signup.name.focus();
                return false;
            }

            if(email=="") {
                alert("Please Enter email");
                document.signup.email.focus();
                return false;
            }

            if(email<3) {
                alert("Please Enter Your Correct email");
                document.signup.email.focus();
                return false;
            }

            if(username=="") {
                alert("Please Enter Username");
                document.signup.username.focus();
                return false;
            }

            if(username<5) {
                alert("Please Enter Username at least 5 digit");
                document.signup.username.focus();
                return false;
            }

            if(password=="") {
                alert("Please Enter Your password");
                document.signup.password.focus();
                return false;
            }

            if(!re.test(password)) {
                alert("Error: Password Must Contain Atleast One Number,One Special Character & One Upper Case");
                document.signup.password.focus();
                return false;
              }



            if(rpass =="") {
                alert("Please Enter Your Password Again");
                document.signup.rpass.focus();
                return false;
            }

            if(rpass != password) {
                alert("Password does'nt Matched");
                document.signup.rpass.focus();
                return false;
            }


            else {
                return true;
            }
        }

Answer №1

document.signup.rpass.focus();

This is incorrect as the rpass field does not exist. You should use

document.signup.confirmpassword.focus();

Visit this link for more information.

Answer №2

Add event.stopPropagation(); to the beginning of your JavaScript function.

Answer №3

You should consider making a modification

else {
    return true;
}

change it to a more straightforward

return true;

Your else statement only pertains to the last if. You can omit the else if you are returning false for all scenarios you need to address.

In simpler terms: by first checking all possibilities for an invalid case, you can confidently return true at the end.

Answer №4

Enhance your regular expression with the following code: No parentheses needed

Your initial code

var re = (/^(?=.[A-Z])(?=.[a-z])(?=.[0-9])(?=.[!@#$%^&])[a-zA-Z0-9!@#$%^&]{8,16}$/);

Updated version of the code

var re = /^(?=.[A-Z])(?=.[a-z])(?=.[0-9])(?=.[!@#$%^&])[a-zA-Z0-9!@#$%^&]{8,16}$/;

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

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

Arranging data in a JSON array while handling null values in JavaScript

Here is my JSON array: var jData = [ {id: 1, parent: null}, {id: 2, parent: null}, {id: 3, parent: 1}, {id: 4, parent: 2}, {id: 5, parent: 2}, {id: 6, parent: 1}]; I would like to sort it in the following order (first by id then by parent): [ {id: 1 ...

Display or conceal certain HTML form elements based on the selection made in the previous form element

I need assistance with a function that can dynamically show or hide certain HTML form elements based on the user's previous selection using JavaScript. For example, if a user selects "Bleached" from the Dyingtype drop-down menu, there is no need to di ...

Combining several JSON objects into a single JSON object using JavaScript

I am in need of merging JSON objects from various sources into a single JSON object using JavaScript. For example, I have two JSON objects with different values that I need to combine and add a new value to the final result. json1= { "b":"t ...

When using Javascript innerhtml, it fails to recognize and properly parse Twig tags

I have a function in Twig that retrieves values from a database and displays them in a select box. I am attempting to update the content of the div, but I am facing an issue with innerHTML. When using {{ without quotes, it creates a new line which is flagg ...

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...

No receiving a callback_query update upon user pressing an inline button in the Telegram webhook

When using the node-telegram-bot-api library, I encountered an issue with my Webhook. Although I am able to receive updates when messages are sent, I do not get any updates when a user presses a button in an inline keyboard. class BotController { async ...

Developing a custom function within an iterative loop

Can someone assist me with a coding problem? I have these 4 functions that I want to convert into a loop: function Incr1(){ document.forms[0].NavigationButton.value='Next'; document.PledgeForm.FUDF9.value='Y1'; document.fo ...

How can I stop popup labels from appearing in MapBox GL JS when I don't want them to be visible?

Having created an application using MapBox GL JS, I have placed numerous markers all around the globe. As the mouse hovers over these markers, a description box pops up, which is what I intended. However, I am encountering an issue where these labels flick ...

JavaScript embedded within LD-JSON format

Is it feasible to run JavaScript code within an ld+json script? Like for instance, "window.location.hostname" <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "http://" + window.location.ho ...

Create dynamic automatic titles in HTML with JavaScript

Below is the code snippet to add an image with a link to the home-page and an h1 with the document name (if there isn't one already). This HTML code includes a JavaScript file reference in the <head> section and uses a <h1> tag for the ti ...

Having trouble connecting to Azure SQL server from my Node.js application

I'm attempting to run a basic query to my Azure SQL server from NodeJs, but I'm encountering errors indicating that I cannot establish a connection to the server. The details provided in my code are correct because I've used them successfull ...

When THREE.js repeatedly loads and plays the same animated GLB file in a loop, only the final model that is loaded will

I'm attempting to create a loop of animated butterflies, but I'm encountering an issue where only the first or last butterfly actually animates. I suspect this is due to the need to clone the gltf.scene, but there's a known bug with cloning ...

Tips for organizing and sorting date data in a JSON datatable

I am working with two date input fields: <form id="refresh" method="post" action="income.php"> <input type="text" id="dari" name="dari" /> <input type="text" id="sampai" name="sampai" /> <button type="submit">Refresh</b ...

Utilizing AngularJS to invoke an ng-controller within a nested controller structure

Take a look at this sample code from the cshtml file: <div> <button type="button" ng-click="recalcButton()">Recalc Button</button> </div> <div ng-controller="appealPartialController"> < ...

Retrieve the ID of the nearest div without it being executed twice

I am currently working on implementing a close button using 'onclick' functionality. The goal is to hide the parent ID element when the user clicks the button, as shown below. function displayNone() { var id= $('.btnClose').closest ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

React's .map is not compatible with arrays of objects

I want to retrieve all products from my API. Here is the code snippet for fetching products from the API. The following code snippet is functioning properly: const heh = () => { products.map((p) => console.log(p.id)) } The issue ari ...

Tips for modifying style.display using JavaScript

On my website, the menu is structured like this: <nav id="menu"> <label for="tm" id="toggle-menu">Menu <span class="drop-icon">▾</span></label> <input type="checkbo ...

"Utilizing JQuery to enhance task management by implementing a delete function

I need help figuring out how to create a function that can delete tasks from my todo list. Currently, each task has its own remove button, but I want to implement a single remove button at the bottom that removes checked or crossed out tasks. Any suggestio ...