Is it possible to use Vuelidate for password validation in Vue.js?

I found a helpful reference on How to validate password with Vuelidate?

 validations: {

    user: {
      password: { required, 
        containsUppercase: function(value) {
          return /[A-Z]/.test(value)
        },
        containsLowercase: function(value) {
          return /[a-z]/.test(value)
        },
        containsNumber: function(value) {
          return /[0-9]/.test(value)
        },
        containsSpecial: function(value) {
          return /[#?!@$%^&*-]/.test(value)
        },
        
        
        minLength: minLength(8),maxLength: maxLength(19) },
      confirmPassword: { required, sameAsPassword: sameAs("password") },
    }, 
    }
<input
                  :type="passwordFieldType"
                  v-model="user.password"
                  v-model.trim="$v.user.password.$model"
                  id="password"
                  name="password"
                  class="input-section-three-login"
                  :class="{'is-invalid': validationStatus($v.user.password) }"                  
                  placeholder="Enter new password"
                  :maxlength="maxpassword" 
                  v-on:keypress="isPassword($event)"

                />
                
                
 <button v-on:click="registerMe" :disabled="user.confirmPassword != user.password   " :class="(isDisabled) ? '' : 'selected'" > Register
</button>

Looking for guidance on validating passwords with vuelidate using regex in the validationStatus and checking this validation on button click.

If the password passes the regex validation successfully, I want to move to the next screen. Otherwise, the user should remain on the current screen until successful validation occurs.

Answer №1

Follow the steps below to resolve the issue

Step 1: Adjust the validations as shown below

validations: {
user: {
  password: { required, 
    valid: function(value) {
      const containsUppercase = /[A-Z]/.test(value)
      const containsLowercase = /[a-z]/.test(value)
      const containsNumber = /[0-9]/.test(value)
      const containsSpecial = /[#?!@$%^&*-]/.test(value)
      return containsUppercase && containsLowercase && containsNumber && containsSpecial
    },
    minLength: minLength(9),
    maxLength: maxLength(19),
  },
  confirmPassword: { required, sameAsPassword: sameAs("password") },
},
},

Step 2: Handle the click event of the RegisterMe button

methods: {
registerMe() {
  this.submitted = true;
  this.$v.$touch();
  if (this.$v.$invalid) {
    return false; // stop here if form is invalid
  } else {
    alert("Form Valid. Move to next screen");
  }
},
},

Step 3: Create a compute function to disable the Register button

computed: {
isDisabled() {
  return this.$v.$invalid;
},
},

Step 4: Ensure the HTML template looks like

<form @submit.prevent="registerMe" novalidate>
  <div class="form-group">
    <input
      type="password"
      class="form-control"
      placeholder="Enter Password"
      value=""
      v-model="user.password"
      autocomplete="off"
    />
    <div
      v-if="this.submitted && $v.user.password.$error"
      class="invalid-feedback left">
      <span v-if="!$v.user.password.required">Password is required</span>
      <span v-if="user.password && !$v.user.password.valid">Password must contain at least One Uppercase, One Lowercase, One Number, and One Special Character</span>
      <span v-if="user.password && $v.user.password.valid && !$v.user.password.minLength">Password must have a minimum of 9 characters</span>
      <span v-if="user.password && !$v.user.password.maxLength">Password can have a maximum of 19 characters</span>
    </div>
  </div>
  <div class="form-group">
    <input
      type="password"
      class="form-control"
      placeholder="Confirm Password"
      value=""
      v-model="user.confirmPassword"
      autocomplete="off"
    />
    <div
      v-if="this.submitted && $v.user.confirmPassword.$error"
      class="invalid-feedback left"
    >
      <span v-if="!$v.user.confirmPassword.required"
        >Confirm Password is required</span
      >
      <span
        v-if="
          user.confirmPassword && !$v.user.confirmPassword.sameAsPassword
        "
        >Password and Confirm Password should match</span
      >
    </div>
  </div>
  <input
    type="submit"
    class="btnRegister"
    value="Register"
    :disabled="this.isDisabled"
  />
</form>

DEMO

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

Determine whether I am verified or if the XMLHttpRequest has been directed

When making an XMLHttpRequest to an API secured with OAuth authentication, I encountered a situation where calling the API from a browser without being logged in automatically redirected me to the provider's login page. However, when attempting to ca ...

What is the process for automatically disabling a checkbox based on the condition that the value in another field is 0?

Before we proceed, feel free to check out the jsFiddle example provided: https://jsfiddle.net/1wL1t21s/ In my scenario, there are multiple checkboxes for selecting toppings with a quantity adjustment feature using the plus (+) and minus (-) buttons. Curre ...

Merging two arrays with lodash for a seamless union

Here are two arrays I'm working with: arr1 = [ { "key1": "Value1" }, { "key2": "Value2" }, { "key3": "Test3" }, { ...

I encounter Error 406 and CORS issues when making API calls

I am currently engaged in a project aimed at helping my employer keep track of shipping loads, customers, carriers, and locations. The frontend is built using a react app that enables users to input information regarding loads, customers, etc. On the backe ...

When faced with the scenario of having the hashtag in the href attribute and a browser's back button, it

Hello everyone, I've encountered an issue with the "back" action in my browser. When I click on a link, it takes me to a specific page due to a JavaScript function being called. However, when I hit the back button, it simply removes the "#" from the U ...

Troubleshooting Vue 3 Composition API: Issue with Data Access in V-For Loop

Currently facing an issue with a template I have The problem lies with location.drawnfeatures not updating within the template for unknown reasons. I've verified that the data is correct using console.log, and when I tested the code without 'v-f ...

Enter the variable into the parameter

I'm working with some Javascript code: document.getElementById("Grid").style.gridTemplateRows = "repeat(3, 2fr)"; I'm trying to insert a variable as an argument to modify my CSS style. When I attempt the following: "repe ...

Unable to modify array state with data from another state

Two state objects are at play here. The first is personnel, which consists of an array of 1-object arrays structured like this: [[{}],[{}],[{}],[{}],...]. The second state object is rowItems, where the goal is to extract all objects from the inner arrays o ...

Feeling trapped by the NullPointer Exception bug

I am currently automating the add to cart process on the website "http://www.oyehappy.com" using TestNG POM Structure. I have encountered a NullPointer Exception while handling autosuggestion. The code for my POM Class is as follows: public class productPa ...

Quickly Share Documents within a Folder

I currently have a server set up with the following file structure: - index.js /client -index.html -about.html -signup.html -style.css Within the index.js file, I have implemented an express server. When the user navigates to /, it should display the ...

What exactly does the .proxy() method do in jQuery?

Can you explain the purpose of the jQuery.proxy function in jQuery and describe the scenarios where it is most beneficial? I came across this link, but I'm struggling to grasp its concept fully. ...

What is the best way to properly format letters with accents (such as French letters)?

I have encountered a challenge where I created a PHP file to display French text and then utilized this text in an AJAX file (specifically the responseText). The issue arises when trying to show the French responseText in an alert using JavaScript, as ac ...

Use v-bind to redirect to Localhost rather than the original link

The current button is linked to the data from v-for="book in books". The URL in the database is www.google.com. <md-button v-bind:href="book.url" target="_blank">SEE ORIGINAL</md-button> However, when loading the page on localhost, the butt ...

Leveraging jquery's $.ajax method to send GET values to a PHP endpoint

Is it possible to use an AJAX call to pass a value to a PHP script? For example, if I have the URL example.com/test.php?command=apple, how can I make sure that the code is executed properly on the server side? This is how my code looks like: PHP: <?p ...

Formik React struggling with error management and handling tasks accurately

I am currently using the Formik template to develop a Login Form. onSubmit={( values, { setSubmitting, setErrors /* setValues and other goodies */ } ) => { props.logMeIn(va ...

Efficiently organizing items within a list on Ionic

Currently, I have an ion-list structured as follows: <ion-list *ngFor = "let chat of Chats"> <ion-item (click) = "openChat(chat.id)"> <ion-label> <h2> {{chat.username}} </h2> ...

There was a glitch encountered while constructing (Verifying type validity) with Prisma

There was an issue in the node_modules/@prisma/client/runtime/library.d.ts file on line 1161, specifically error TS1005 where a '?' was expected. 1161 | select: infer S extends object; | ^ 1162 | } & R ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

The save changes feature is not effectively syncing with the database

So, I have a button that triggers a javascript function, which initiates an AJAX request to call an actionresult that is supposed to update my database. Javascript Function function changeDepartment() { // Initializing and assigning variables va ...

What is the best way to present JSON data retrieved from an API on different pages using Next.js?

I am currently working on two pages that are connected: one is an API page called secured.js (where user session data is processed) and the other is a normal page also named secured.js (which displays the processed content from the API page). This is the ...