使用Vue 2进行客户端表单验证

时间:2017-01-28 22:13:22

标签: validation vue.js vuejs2

我正在使用Laravel 5.3Vue 2开发一个应用程序我通过form-validation实施了Vue 2但是它没有检查任何错误的请求客户端它首先将每个请求发送到服务器,然后显示从服务器发回的错误,在下面你可以找到我的代码

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);
    }
}

这就是`Vue类

` `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();
            }
        }
    });`

这是我的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>

问题: 我需要以一种方式修改代码,首先它在客户端进行检查,如果发现任何错误,则阻止将请求发送到服务器,不要将每个请求发送到服务器,然后显示从服务器发回的错误服务器

1 个答案:

答案 0 :(得分:4)

您可以在设置之前使用任何类型的客户端验证,在提交表单之前,您可以从Form类中获取数据并使用vanilla javascript或任何其他验证库对其进行验证。

我们以validate.js为例:

您可以在onSubmit方法中执行

 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));
},