JavaScript for validating usernames and passwords

I am facing a simple issue where I am unsure of what went wrong.

Here is the code snippet I am working with:

    function validateForm() 
    {
        var validation = true;
        validation &= validateUsername();
        validation &= validatePassword();
        return validation? true:false;
    }

    function validateUsername()
    {
        var username = $('#username').val();

        if( username == "" )
        {
            alert("Login failed, Please enter your username");
            return false;
        }

        else if( username != "username" )
        {
            alert("Login failed, Username Incorrect");
            return false;
        }

        else
        {
            return true;
        }

    }

    function validatePassword()
    {

        var password = $('#pass').val();

        if(password != "password")
        {
            alert("Login failed, Password is incorrect");
            return false;
        }

        else if(password == "")
        {
            alert("Login failed, Please enter your password");
            return false;
        }

        else
        {
            return true;
        }
    }

When I do not enter a password, instead of getting an alert prompting me to enter the password, it alerts that the password is incorrect. Why is it not executing all the conditions I have defined in the code?

Answer №1

Make sure to adjust the order of conditions when validating a password. It is important to check for an empty string before verifying the correct password:

function validatePassword() {

   var password = $('#pass').val();

   if(password == "") {
       alert("Login failed, Please enter your password");
       return false;
   } else if(password != "password") {
       alert("Login failed, Password is incorrect");
       return false;
   } else {
       return true;
   }
}

Currently, the code checks for the incorrect password first. Since an empty string is not the correct password, it would be more efficient to address this condition before checking for the correct password.

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

What are the recommended methods for updating data using mongoose?

There are two methods for updating data with mongoose. Using model methods, such as User.updateOne({username}, {$set: {age}}) Finding the document, making changes to its properties, and saving it. Like this: const user = await User.findById(userId) user. ...

"Ensuring Mongoose pre-save functionality correctly enhances field without triggering updates

I am working with a Video schema that looks like this: const videoSchema = new mongoose.Schema({ cover: { // image url type: String, required: true, }, category: [{ type: mongoose.Schema.Types.ObjectId, ref: &apo ...

When opting for "Not now" in Firefox, the error callback in getUserMedia is not activated

I am currently working on a script to detect when the user either allows or denies the use of a microphone using the getUserMedia API. UPDATE: To better illustrate the issue I am facing, I have created a fiddle: http://jsfiddle.net/4rgRY/ navigator.getUs ...

Raising the css value for each element that is impacted

I am faced with an infinite number of elements that I need to arrange next to each other. Each element has a class called "box". My goal is to separate each box by 10px increments, meaning the first element will have a left property of 0px, the second 10px ...

Leveraging the result of one ajax function within a different ajax function

My current project involves the following steps: 1. User creates a template with various elements. 2. When the user clicks a button: *The first ajax function establishes a new entry in the custom template database. *The second ajax function retrieves the ...

using selenium to interact with elements within the window object

I'm a newcomer to selenium and javascript and looking to incorporate the VisualEvent javascript into pages opened in a selenium-controlled browser. My goal is to access its variables from selenium in java. I've successfully completed the first ph ...

Issue: template.config.js not found during creation of a React Native project on version 0.59.9

Every time I attempt to start a new react native project with version 0.59.9, an error pops up that says: Error: Couldn't find the "/var/folders/zc/h93bvpb573q24_5ynvgkn1wc0000gn/T/rncli-init-template-0YT6FZ/node_modules/react-native/template.config ...

Is it possible to use jQuery to set a value for a form control within an Angular component?

I'm currently working on an Angular 5 UI project. In one of my component templates, I have a text area where I'm attempting to set a value from the component.ts file using jQuery. However, for some reason, it's not working. Any suggestions o ...

Mastering the art of styling strings in the Terminal with Chalk - the ultimate guide

I've been trying to use the chalk terminal string styling package in iTerm2, but I'm not seeing any colored string results despite following all the installation steps. Even a simple console log like console.log("hello"); in my chalk.js file isn& ...

Encountering errors while attempting to render MUI components in jsdom using react testing library within a mocha test

Due to the lack of maintenance and support for React 18+ in enzyme, I am faced with the task of migrating over 1750 unit tests to work with react-testing-library and global-jsdom. This migration is necessary so that our application can continue running on ...

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...

The modal remains visible

Has anyone encountered a problem with hiding a Bootstrap modal based on form validation in JavaScript? I'm facing an issue where the submit function is not executed when I click the button. I've attempted using onsubmit=validateForm(), but it doe ...

To toggle between two scope variables within a view when one is not defined

In my application, I am utilizing two scope variables: $scope.banner and $scope.defaultBanner. The banner is fetched using a service, but in cases where the banner file does not exist, the variable will be empty as the service returns nothing. My goal is ...

Deciphering unconventional JSON formats

Can anyone identify the format of this JSON (if it even is JSON!) from the code snippet below? I've extracted this data from a website's HTML and now I'm struggling to parse it in C# using a JSON parser. The data requires significant preproc ...

Most effective method for integrating ajax URLs and browser history in a unique Joomla component

I have been given the task of enhancing the search functionality of a custom Joomla component that is solely operated through AJAX. Currently, the search does not handle URL/query strings, preventing users from using the browser back button to return to pr ...

Removing classes from multiple cached selectors can be achieved by using the .removeClass

Currently working on enhancing some JavaScript/jQuery code by storing selectors in variables when they are used more than once to improve performance, for example: var element = $("#element"); element.hide(); However, I am facing difficulties while tryin ...

Changing the image source dynamically at runtime using JavaScript and jQuery

Is it possible to dynamically change the source of an image using jQuery during runtime? I have set up a jsfiddle to demonstrate my question. I am attempting to load the image specified in the variable $newsrc when a button is clicked. However, I am unsure ...

Instead of using a v-if condition, add a condition directly in the Vue attribute

Apologies for the unclear title, as I am unsure of what to name it with regards to my current issue, I am attempting to create a component layout using vuetify grid. I have a clear idea of how to do this conventionally, like so: <template> <v-fl ...

I'm experiencing very slow page load times in dev mode with Next.js (30s+). What could be the reason behind this sluggishness?

QUESTION: Encountering a similar issue (but with different files): https://github.com/vercel/next.js/discussions/17977 I've already tried all the suggestions provided in that discussion. This is what the page load process looks like in development ...

Passing all emitted events from Vue 3 child component to its parent - A complete guide

My Vue components are structured as follows: <TopParent> <!-- Listening for events from EventProducer here --> <Child_1> <Child_2> <Child_3> ... <Child_N> <EventProducer /> &l ...