Siavosh
Siavosh

Reputation: 2354

Client-Side form validation with Vue 2

I am developing an application with with Laravel 5.3 and Vue 2 I implemented a form-validation via Vue 2 but the it doesn't check the request for any errors on client-side it firstly lets every single request to be sent to the server and then displays the errors which are sent back from the server, in the following you can find my code

class Form {
    constructor(data) {
        this.originalData = data;

        for (let field in data) {
            this[field] = data[field];
        }

        this.errors = new Errors();
    }

    data() {
        let data = {};
        for (let property in this.originalData) {
            data[property] = this[property];
        }

        return data;
    }

    reset() {
        for (let field in this.originalData) {
            this[field] = '';
        }

        this.errors.clear();
    }

    post(url) {
        return this.submit('post', url);
    }


    submit(requestType, url) {
        return new Promise((resolve, reject) => {
            axios[requestType](url, this.data())
                 .then(response => {
                     this.onSuccess(response.data);
                     resolve(response.data);
                 })
                 .catch(error => {
                     this.onFail(error.response.data);
                     reject(error.response.data);
                 });
        });
    }

    onSuccess(data) {
        alert(data.message);

        this.reset();
    }

    onFail(errors) {
        this.errors.record(errors);
    }
}

and this is the `Vue class

` `new Vue({
        el: "#form",
        data: {
            form: new Form({
                name: '',
                description: ''
            })
        },
        methods: {
            onSubmit() {
                this.form.post('/admin/category');
                //.then(response => alert('Item created successfully.'));
                //.catch(errors => console.log(errors));
            },

            onSuccess(response) {
                alert(response.data.message);

                form.reset();
            }
        }
    });`

and this is my HTML form

<form method="post" id="form" action="{{ url('admin/category') }}" '
@submit.prevent="onSubmit" @keydown="form.errors.clear($event.target.name)">
                    {{ csrf_field() }}


          <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" id="name" name="name" 
 v-model="form.name" placeholder="Name">
                    <span class="help is-danger" 
  v-if="form.errors.has('name')" v-text="form.errors.get('name')"></span>
                </div>
                <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" id="description" name="description" 
v-model="form.description" placeholder="Description"></textarea>


                    <span class="help is-danger" 
  v-if="form.errors.has('description')" 
  v-text="form.errors.get('description')"></span>
                </div>
                <button type="submit" class="btn btn-default" :disabled="form.errors.any()">Create New Category</button>
            </form>

Question: I need to modify the code in a way that firstly it checks on client side and if it finds any errors prevent the request from being sent to the server not letting every single request to be sent to server and then displays the errors sent back from the server

Upvotes: 2

Views: 1912

Answers (1)

AfikDeri
AfikDeri

Reputation: 2109

You can use any type of client side validation with your setup, just before you submit the form you can take the data from the Form class and validate it with vanilla javascript or any other validation library.

Let's use validate.js as an example:

in your onSubmit method you can do:

 onSubmit() {

 //get all the fields
 let formData = this.form.data();

 //setup the constraints for validate.js
 var constraints = {
  name: {
    presence: true
  },
  description: {
    presence: true
  }
};

//validate the fields
validate(formData, constraints);  //you can use this promise to catch errors

//then submit the form to the server
this.form.post('/admin/category');
    //.then(response => alert('Item created successfully.'));
    //.catch(errors => console.log(errors));
},

Upvotes: 3

Related Questions