T dhanunjay
T dhanunjay

Reputation: 820

How to validate confirm password field at 4th character in Vuejs?

    password: {
      required: required,
      minLength: minLength(8),
    },
    <!-- Password -->
    <label class="form__group is-required">
      <span class="form__label">Password</span>
      <input
        class="form__input"
        type="password"
        name="form-password"
        v-model="password"
        @input="$v.password.$touch"
      />
      <p v-if="$v.password.$dirty">
        <span class="form__alert" v-if="!$v.password.required">Required.</span>
        <span class="form__alert" v-if="!$v.password.minLength">
          {{ $v.password.$params.minLength.min }} letters at least.
        </span>
      </p>
    </label>
    <!-- Repeat Password -->
    <label class="form__group is-required">
      <span class="form__label">Repeat<br />password </span>
      <input
        class="form__input"
        type="password"
        name="form-repeat-password"
        v-model="repeatPassword"
        @input="$v.repeatPassword.$touch"
      />
      <p v-if="$v.repeatPassword.$dirty">
        <span class="form__alert" v-if="!$v.repeatPassword.required"
          >Required.</span
        >
        <span class="form__alert" v-if="!$v.repeatPassword.sameAsPassword">
          Must be identical.
        </span>
      </p>
    </label>
    </div>
  </form>

repeatPassword: {
  required: required,
  sameAsPassword: (value, vm) =>
    value === vm.password.substring(0, value.length),
},

I want to validate confirm password field at 4th character in Vuejs? At present it is checking from the first character, tried using value.length < 5 but it doesn't work.

I have updated my input fields with vuelidate code

Upvotes: 0

Views: 808

Answers (2)

Loi Nguyen Huynh
Loi Nguyen Huynh

Reputation: 9948

If you don't want to display the validation when repeatPassword contains less than 4 characters (it's weird why you need that btw), then just add it && repeatPassword.length >= 4 on the code like so.

<p v-if="$v.repeatPassword.$dirty && repeatPassword.length >= 4"> 
<!-- only display the validation when length >= 4 -->
  <span class="form__alert" v-if="!$v.repeatPassword.required"
    >Required.</span
  >
  <span class="form__alert" v-if="!$v.repeatPassword.sameAsPassword">
    Must be identical.
  </span>
</p>

Upvotes: 1

Sudarshan Rai
Sudarshan Rai

Reputation: 306

Here is a simple If()else{} way

      watch: {
        repeatPassword(v) {
//checking repeat password length is 4 or greater then 4
          if(v.length >= 4){
//then checking if repeat password is same as password
            if(v === this.password){
              console.log('Passwords are same')
            }else{
              console.log('No a same password')
            }
          }else{
            console.log('validate start after Repeat password length 4')
          }
        },
      },

working example: demo

Upvotes: 0

Related Questions