zxtanzxzx
94
1
Vue

Form validation with vue component and vee-validate

Posted 1 month ago by zxtanzxzx

How to make it so vue component in a form tag trigger vee-validate for validation

when i click submit. only validation in the blade triggers and error message is shown...i want to valdiate the field within the vue also. How to do it? form.blade.php

        <form method="POST" action="{{route('project.registration')}}" name="regisForm" id="regisForm" @submit="validateBeforeSubmit(e)">
            {{ csrf_field() }}
            <ul>
                <li @v-for="(error in errors)" :key="(error, index)">@{{ error }}</li>
            </ul>
            <div class=" text-center" style="margin-top:1rem;">
                <div><strong>Project Information</strong></div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="projectTitle">Project Title</label><span style="color:red"> *</span>
                    <input v-validate.continues="'required'" type="text" id="projectTitle" name="projectTitle" class="form-control"
                        value="{{ old('projectTitle')}}" autofocus style="text-transform:uppercase">
                        <div @v-if="errors.has('projectTitle')" class="alert-danger">@{{errors.first('projectTitle')}}</div>
                    @if ($errors->has('projectTitle'))
                    <div class=" " role="">
                        Project Title is <strong class="" style="color:red">Required</strong>
                    </div>
                    @endif
                </div>
                <div class="form-group col-md-6">
                    <label for="projectCategory">
                        Project Category
                    </label><span style="color:red"> *</span>
                    <select name="projectCategory" id="projectCategory" class="form-control">
                <option value="1">Students engaged in the projects with potential for
                            commercialization</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for="projectDesc">Project Description</label><span style="color:red"> *</span>
                    <textarea v-validate.continues="'required|min:10'" class="form-control" id="projectDesc" name="projectDesc" cols="30" rows="10" value="">{{ old('projectDesc')}}</textarea>
                    <div @v-if="errors.has('projectDesc')" class="alert-danger">@{{errors.first('projectDesc')}}</div>
                    <span class="focus-border"></span>
                </div>
            </div>
            <div class=" text-center" style="margin-top:1rem;">
                <strong>Supervisor Information</strong>
            </div>
            <supervisor ref="supervisor"></supervisor>

<div class="form-row">
                <div class="form-group col-md-1">
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
                <div class="form-group col-md-8 offset-md-1">
                    <button type="reset" class="btn btn-light" style="text-decoration:underline; width:5rem">Reset</button>
                </div>
            </div>
</form>

teamleader.vue

<template>
  <div class="app">
    <div class>
      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="leaderName">Name</label>
          <span style="color:red">*</span>
          <input
            class="form-control"
            type="text"
            name="leaderName"
            id="leaderName"
            style="text-transform:uppercase"
            v-validate="'required'"
            v-model="teamleader.teamleaderName"
          >
          <div v-if="errors.has('leaderName')">{{errors.first('leaderName')}}</div>
        </div>
        <div class="form-group col-md-6">
          <label for="leaderID">ID/Alumni ID</label>
          <span style="color:red">*</span>
          <masked-input
            class="form-control"
            type="text"
            name="leaderID"
            id="leaderID"
            :mask="[/\d/,/\d/,/[wW]/,/\w/,/\w/, /\d/, /\d/, /\d/, /\d/, /\d/]"
            :guide="true"
            style="text-transform:uppercase"
            v-model="teamleader.teamleaderID"
          ></masked-input>
        </div>
      </div>

      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="leaderICNo">IC No.</label>
          <span style="color:red">*</span>
          <masked-input
            type="text"
            name="leaderICNo"
            id="leaderICNo"
            class="form-control"
            v-model="teamleader.teamleaderICNo"
            :mask="[/\d/,/\d/,/\d/,/\d/,/\d/,/\d/,'-',/\d/,/\d/,'-',/\d/,/\d/,/\d/,/\d/]"
            :guide="true"
          ></masked-input>
        </div>
        <div class="form-group col-md-6">
          <label for="leaderEmail">Email</label>
          <input
            class="form-control"
            type="text"
            name="leaderEmail"
            id="leaderEmail"
            v-model="teamleader.teamleaderEmail"
          >
        </div>
      </div>
      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="leaderHp">HP No.</label>
          <span style="color:red">*</span>
          <masked-input
            class="form-control"
            type="text"
            name="leaderHp"
            id="leaderHp"
            v-model="teamleader.teamleaderHp"
            :mask="[/[0]/,/[1]/,/[\d]/, '-',/\d/,/\d/,/\d/,' ',/\d/,/\d/,/\d/,/\d/,/\d/]"
            :guide="false"
          ></masked-input>
        </div>
        <div class="form-group col-md-6">
          <label for="leaderDepartment">Faculty/Center/Alumni</label>
          <span style="color:red">*</span>
          <select
            name="leaderDepartment"
            id="leaderDepartment"
            class="form-control"
            v-model="teamleader.teamleaderDepartment"
            @change="getLevel()"
          >
          </select>
        </div>
      </div>
      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="leaderStudyLevel">Study Level</label>
          <span style="color:red">*</span>
          <select
            name="leaderStudyLevel"
            id="leaderStudyLevel"
            class="form-control"
            v-model="teamleader.teamleaderSelectedLevel"
            :disabled="teamleader.levelOptionDisable"
            @change="getProgramme()"
          >
            <option
              v-for="(level, index) in teamleader.teamleaderLevel"
              :key="level"
              :value="level"
              v-bind:selected="index === 0 ? 'selected' : false"
            >{{ level }}</option>
          </select>
        </div>
        <div class="form-group col-md-6">
          <label for="leaderProgramme">Programme</label>
          <span style="color:red">*</span>
          <label>{{ teamleader.teamleaderSelectedLevel }}</label>
          <select
            class="form-control"
            name="leaderProgramme"
            id="leaderProgramme"
            v-model="teamleader.teamleaderProgramme"
            :disabled="teamleader.programmeOptionDisable"
          >
            <option
              v-for="programme in teamleader.programmesList"
              :key="programme"
              v-text="programme"
              :value="programme"
            >{{programme}}</option>
          </select>
        </div>
      </div>
      <br>
    </div>
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      teamleader: {
        teamleaderName: "",
        teamleaderICNo: "",
        teamleaderEmail: "",
        teamleaderHp: "",
        teamleaderDepartment: "",
        teamleaderProgramme: "",
        teamleaderLevel: [],
        teamleaderSelectedLevel: "",
        programmesList: [],
        programmeOptionDisable: true,
        levelOptionDisable: true
      },
      test: "",
      teamleader_level: "diploma",
      value2: "test",
      url: "/get/programme/",
      undergraduateLevel: ["Degree", "Diploma"],
      preULevel: ["A Level", "Foundation"],
      postgraduateLevel: ["Master", "Doctorate"],
      alumni: ["Alumni"]
    };
  },
  methods: {
    getLevel() {
      if (this.teamleader.teamleaderDepartment == "Alumni") {
        this.teamleader.programmeOptionDisable = true;
        this.teamleader.levelOptionDisable = true;
        this.teamleader.programmesList = this.alumni;
        this.teamleader.teamleaderLevel = this.alumni;
      } else if (this.teamleader.teamleaderDepartment == "CPSR") {
        this.teamleader.programmeOptionDisable = false;
        this.teamleader.levelOptionDisable = false;

        this.teamleader.teamleaderLevel = this.postgraduateLevel;

        this.url = this.url + this.teamleader.teamleaderDepartment + "/master";
        axios
          .get(this.url)
          .then(response => (this.teamleader.programmesList = response.data));

        this.url = "/get/programme/";
      } else if (this.teamleader.teamleaderDepartment == "CPUS") {
        this.teamleader.programmeOptionDisable = false;
        this.teamleader.levelOptionDisable = false;
        this.teamleader.teamleaderLevel = this.preULevel;

        this.url = this.url + this.teamleader.teamleaderDepartment + "/master";
        axios
          .get(this.url)
          .then(response => (this.teamleader.programmesList = response.data));

        this.url = "/get/programme/";
      } else {
        this.teamleader.programmeOptionDisable = true;
        this.teamleader.levelOptionDisable = false;
        this.teamleader.teamleaderLevel = this.undergraduateLevel;

        this.url = "/get/programme/";
      }
    },
    getProgramme() {
      //Error handling website

      this.url = "/get/programme/";

      this.teamleader.programmeOptionDisable = false;

      this.url =
        this.url +
        this.teamleader.teamleaderDepartment +
        "/" +
        this.teamleader.teamleaderSelectedLevel;
      axios
        .get(this.url)
        .then(response => (this.teamleader.programmesList = response.data));
    }
  }
};
</script>

app.js


/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Import and use vue extensions 
 */

import VeeValidate from 'vee-validate';//https://baianat.github.io/vee-validate/
import MaskedInput from 'vue-text-mask'//https://github.com/text-mask/text-mask

const config = {
    aria: true,
    classNames: {},
    classes: false,
    delay: 0,
    dictionary: null,
    errorBagName: 'errors', // change if property conflicts
    events: 'input|blur',
    fieldsBagName: 'fields',
    i18n: null, // the vue-i18n plugin instance
    i18nRootKey: 'validations', // the nested key under which the validation messages will be located
    inject: true,
    locale: 'en',
    validity: false
  };
  
Vue.use(VeeValidate, config);

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('masked-input', MaskedInput);
Vue.component('example-component', require('./components/ExampleComponent.vue').default);
Vue.component('member', require('./components/Member.vue').default);
Vue.component('supervisor', require('./components/Supervisor.vue').default);
Vue.component('team-leader', require('./components/TeamLeader.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({

    el: '#app',
    methods:{
        validateBeforeSubmit(e){
          supervisor.callMethod();
            this.$validator.validateAll().then((result) => {
                if (!(result)) {
                  e.preventDefault();
                  // eslint-disable-next-line
                  alert('Form not Submitted!');
                  // return;
                }
                alert('Form Submitted!');
              });
        }
    }
});

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.