【发布时间】:2018-10-06 18:16:29
【问题描述】:
【问题讨论】:
-
你需要使用 vuejs 或 jquery,google 一下
标签: php laravel passwords password-protection
【问题讨论】:
标签: php laravel passwords password-protection
您可以使用 Vue.js 和 axios 来验证和显示错误。在控制器中有一个名为 /validate-data 的路由来验证数据。
app.js 文件:
import Vue from 'vue'
window.Vue = require('vue');
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}
class Errors {
constructor() {
this.errors = {};
}
get(field) {
if (this.errors[field]) {
return this.errors[field][0];
}
}
record(errors) {
this.errors = errors;
}
clear(field) {
delete this.errors[field];
}
has(field) {
return this.errors.hasOwnProperty(field);
}
any() {
return Object.keys(this.errors).length > 0;
}
}
new Vue({
el: '#app',
data:{
errors: new Errors(),
model: {
business-name: '',
business-description: '',
business-phone: ''
},
},
methods: {
onComplete: function(){
axios.post('/validate-data', this.$data.model)
// .then(this.onSuccess)
.catch(error => this.errors.record(error.response.data.errors));
},
}
});
使用控制器中的方法创建一个名为 /validate-data 的路由,执行标准验证
$this->validate(request(), [
'business-name'=> 'required|string|max:255',
'business-description'=> 'required|string',
'business-phone' => 'nullable|phone|numeric',
'business-email' => 'nullable|email',
'business-street'=> 'required|string',
'business-city' => 'required|string',
'business-state' => 'required|string|max:2',
'business-zip' => 'required|min:5|max:5|numeric'
]
);
然后使用与 vue.js 数据模型字段对应的 v-model 在视图文件中创建输入。在它下面,添加一个带有错误类(例如基本的红色错误样式)的跨度,仅在错误存在时才会显示。例如:
<input type="text" name="business-name" v-model="model.business-name" class="input">
<span class="error-text" v-if="errors.has('business-name')" v-text="errors.get('business-name')"></span>
不要忘记在视图文件的页脚中包含 app.js 文件。记得包含标签,然后运行 npm run watch 来编译 vue 代码。这将允许您验证其输入字段下的所有错误。
忘记添加了,有一个带有@onclick="onComplete" 的按钮来运行验证方法。
【讨论】: