Home > Net >  Simple validation in vue
Simple validation in vue

Time:10-26

I am beginner web developer. I make my first application in vue project.

I have this code:

<template>
  <CRow>
    <CCol col="12" lg="6">
      <CCard no-header>
        <CCardBody>
          <h3>
            Create Note
          </h3>
          <CAlert
            :show.sync="dismissCountDown"
            color="primary"
            fade
          >
            ({{ dismissCountDown }}) {{ message }}
          </CAlert>

          <CInput label="Title" type="text" id="title" placeholder="Title" v-model="note.title"></CInput>

          <CInput textarea="true" label="Content" id="content" :rows="9" placeholder="Content.."
                  v-model="note.content"></CInput>

          <CInput label="Applies to date" type="date" id="applies_to_date" v-model="note.applies_to_date"></CInput>

          <CSelect id="status_id"
                   label="Status"
                   :value.sync="note.status_id"
                   :plain="true"
                   :options="statuses"
          >
          </CSelect>
          <CInput label="Note type" type="text" id="note_type" v-model="note.note_type"></CInput>

          <template>
            <div id="app">
              <ckeditor v-model="editorData" :config="editorConfig"></ckeditor>
            </div>
          </template>

          <CButton color="primary" @click="store()">Create</CButton>
          <CButton color="primary" @click="goBack">Back</CButton>
        </CCardBody>
      </CCard>
    </CCol>
  </CRow>
</template>

import axios from 'axios';
import Vue from 'vue';
import CKEditor from 'ckeditor4-vue';

Vue.use(CKEditor);

export default {
  name: 'EditUser',
  props: {
    caption: {
      type: String,
      default: 'User id'
    },
  },
  data: () => {
    return {
      note: {
        title: '',
        content: '',
        applies_to_date: '',
        status_id: null,
        note_type: '',
      },
      statuses: [],
      message: '',
      dismissSecs: 7,
      dismissCountDown: 0,
      showDismissibleAlert: false,

      editorData: '',
      editorConfig: {
        // The configuration of the editor.
        filebrowserImageBrowseUrl: Vue.prototype.$apiAdress '/api/laravel-filemanager?token='   localStorage.getItem("api_token"),
        filebrowserImageUploadUrl: Vue.prototype.$apiAdress '/api/laravel-filemanager/upload?type=Images&amp;_token=&token='   localStorage.getItem("api_token"),
        filebrowserBrowseUrl: Vue.prototype.$apiAdress '/api/laravel-filemanager?type=Files&token='   localStorage.getItem("api_token"),
        filebrowserUploadUrl: Vue.prototype.$apiAdress '/api/laravel-filemanager/upload?type=Files&amp;_token=&token='   localStorage.getItem("api_token"),
        height: 500,
        language: 'pl',
        //extraPlugins: 'facebookvideo, youtube, html5video',
        editorUrl: "facebookvideo.js",
        extraPlugins: 'a11yhelp,about,basicstyles,bidi,blockquote,clipboard,colorbutton,colordialog,contextmenu,copyformatting,dialogadvtab,div,editorplaceholder,elementspath,enterkey,entities,exportpdf,filebrowser,find,flash,floatingspace,font,format,forms,horizontalrule,htmlwriter,iframe,image,indentblock,indentlist,justify,language,link,list,liststyle,magicline,maximize,newpage,pagebreak,pastefromgdocs,pastefromlibreoffice,pastefromword,pastetext,preview,print,removeformat,resize,save,scayt,selectall,showblocks,showborders,smiley,sourcearea,specialchar,stylescombo,tab,table,tableselection,tabletools,templates,toolbar,undo,uploadimage, wysiwygarea,autoembed,image2,embedsemantic',
        image2_alignClasses: ['image-align-left', 'image-align-center', 'image-align-right'],
        image2_disableResizer: true,
      }
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
      // this.$router.replace({path: '/users'})
    },
    store() {
      let self = this;
      axios.post(this.$apiAdress   '/api/notes?token='   localStorage.getItem("api_token"),
        self.note
      )
        .then(function (response) {
          self.note = {
            title: '',
            content: '',
            applies_to_date: '',
            status_id: null,
            note_type: '',
          };
          self.message = 'Successfully created note.';
          self.showAlert();
        }).catch(function (error) {
        if (error.response.data.message == 'The given data was invalid.') {
          self.message = '';
          for (let key in error.response.data.errors) {
            if (error.response.data.errors.hasOwnProperty(key)) {
              self.message  = error.response.data.errors[key][0]   '  ';
            }
          }
          self.showAlert();
        } else {
          console.log(error);
          self.$router.push({path: 'login'});
        }
      });
    },
    countDownChanged(dismissCountDown) {
      this.dismissCountDown = dismissCountDown
    },
    showAlert() {
      this.dismissCountDown = this.dismissSecs
    },
  },
  mounted: function () {
    let self = this;
    axios.get(this.$apiAdress   '/api/notes/create?token='   localStorage.getItem("api_token"))
      .then(function (response) {
        self.statuses = response.data;
      }).catch(function (error) {
      console.log(error);
      self.$router.push({path: 'login'});
    });
  }
}

I need add to my project validation with alert box when input is empty. I need required for title and content. When user click button "Create" I need check this inputs. If it's empty - then I need show alert().

How can I make it?

Please help me :)

CodePudding user response:

You can make method:

checkInputs() {
  if(!this.note.title) {
    this.message = 'pls enter title'
    this.showAlert()
    return true
  }
  if(!this.note.content) {
    this.message = 'pls enter content'
    this.showAlert()
    return true
  }
  return false
}

and in store method:

store() {
  if(this.checkInputs()) return
  ...
  • Related