Search code examples
vue.jsvuelidate

Form validation not displaying error on screen with Vuelidate


I'm trying to add some validations with Vuelidate to a login form. When I leave the username field blank, I'm expecting to see a warning displayed saying "Name is required", but nothing is showing up.

It's not progressing to the next step (which is what I want), so I'm assuming that the validation is working, I'm just not getting the message displayed on the screen. I ran it in debug mode and I'm not getting any errors, is there something I've done wrong?

<template>
    <div>
        <h3>Sign in</h3>
        <div class="row" v-if="errorMessage">
            <div class="alert alert-danger"><p>{{ errorMessage }}</p></div>
        </div>
        <div class="row" v-if="successMessage">
            <div class="alert alert-success"><p>{{ successMessage }}</p></div>
        </div>
        <form @submit.prevent="OnLogin">
            <div class="form-group">
                <label for="userSigninLogin">Email</label>
                <input name="username" type="text"
                class="form-control"
                :class="{ 'is-invalid': submitted && $v.apiRequest.username.$error }"
                placeholder="Enter your email" v-model="apiRequest.username">
            </div>
            <div class="form-group">
                <label for="userSigninPassword">Password</label>
                <input name="password" type="password"
                class="form-control" id="userSigninPassword"
                placeholder="Enter your password" v-model="apiRequest.password">
            </div>
            <button type="submit" class="btn btn-primary">Sign in</button>
            <div v-if="submitted" && !$v.apiRequest.username.required
                class="alert alert-danger"><p>Name is required</p></div>
            <div class="row" v-if="submitted" && !$v.apiRequest.username.required>
              <div class="alert alert-danger"><p>Name is required</p></div>
            </div>
        </form>
    </div>
</template>

<script>
import { required, minLength } from 'vuelidate/lib/validators';

export default {
  data() {
    return {
      apiRequest: new this.$request({
        username: '',
        password: '',
      }),
      errorMessage: '',
      successMessage: '',
      submitted: false,
    };
  },
  validations: {
    apiRequest: {
      username: {
        required,
        minLength: minLength(2),
      },
    },
  },
  methods: {
    OnLogin() {
      this.submitted = true;
      this.apiRequest.addStore(this.$store);
      this.apiRequest.post('login')
        .then((response) => {
          this.successMessage = response;
          this.errorMessage = '';
        })
        .catch((errors) => {
          this.errorMessage = errors;
          this.successMessage = '';
        });
    },
  },
};
</script>

Solution

  • Follow the steps it helps you to resolve your issue. You forgot to add validation on button click and also there is template error in displaying error message.

    Step 1: HTML template

    <div id="app">
      <h3>Sign in</h3>
      <div class="row" v-if="errorMessage">
        <div class="alert alert-danger">
          <p>{{ errorMessage }}</p>
        </div>
      </div>
      <div class="row" v-if="successMessage">
        <div class="alert alert-success">
          <p>{{ successMessage }}</p>
        </div>
      </div>
      <form @submit.prevent="OnLogin">
        <div class="form-group">
          <label for="userSigninLogin">Email</label>
          <input name="username"
            type="text" class="form-control" :class="{ 'is-invalid': submitted && $v.apiRequest.username.$error }"
            placeholder="Enter your email" v-model="apiRequest.username" />
          <div v-if="submitted && $v.apiRequest.username.$error" class="alert alert-danger">
            <span v-if="!$v.apiRequest.username.required">Username is Required</span>
            <span v-if="!$v.apiRequest.username.minLength">Enter Minimum 6 character</span>
            <span v-if="$v.apiRequest.username.minLength && !$v.apiRequest.username.email">Enter Valid Email address</span>
          </div>
        </div>
        <div class="form-group">
          <label for="userSigninPassword">Password</label>
          <input name="password" type="password" class="form-control"
            id="userSigninPassword" placeholder="Enter your password" v-model="apiRequest.password" />
          <div class="row" v-if="submitted && !$v.apiRequest.password.required">
            <span class="alert alert-danger">Password is required</span>
          </div>
        </div>
        <button type="submit" class="btn btn-primary">Sign in</button>
      </form>
    </div>
    

    Step 2: Initalize your modal data

    data() {
        return {
          apiRequest: {
            username: "",
            password: "",
          },
          errorMessage: "",
          successMessage: "",
          submitted: false,
        };
      },
    

    Step 3: Add validations rule

    validations: {
        apiRequest: {
          username: {
            required,
            minLength: minLength(6),
            email,
          },
          password: { required },
        },
     },
    

    Step 4: Add form submit method

    methods: {
        OnLogin() {
          this.submitted = true;
          this.$v.$touch();
          if (this.$v.$invalid) {
            return; // stop here if form is invalid
          }
          this.apiRequest
            .post("login")
            .then((response) => {
              this.successMessage = response;
              this.errorMessage = "";
            })
            .catch((errors) => {
              this.errorMessage = errors;
              this.successMessage = "";
            });
        },
      },
    

    DEMO