)
我有一个关于表格验证的问题。
这是我的表格:
<form class = "uk-form-row" v-validator="formTax"@submit.prevent = "add | valid">
<div class="uk-grid">
<div class="uk-width-1-4">
<select class = "uk-form-small" name="countrycode" v-model = "newTax.countrycode" v-validate:required>
<option v-for = "country in countries" value = "{{ $key }}" :disabled = "vatMatch($key)">
{{country}}
</option>
</select>
<p class="uk-form-help-block uk-text-danger" v-show="formTax.countrycode.invalid">{{ 'Field cannot be blank.' | trans }}</p>
</div>
<div class="uk-width-1-4">
<input class = "uk-input-large" type = "number"
placeholder = "{{ 'Companies' | trans }}" name="companies" v-model = "newTax.companies" number v-validate:required>
<p class="uk-form-help-block uk-text-danger" v-show="formTax.companies.invalid">{{ 'Field cannot be blank.' | trans }}</p>
</div>
<div class="uk-width-1-4">
<input class = "uk-input-large" type = "number"
placeholder = "{{ 'Individuals' | trans }}" name="individuals" v-model = "newTax.individuals"
number v-validate:required>
<p class="uk-form-help-block uk-text-danger" v-show="formTax.individuals.invalid">{{ 'Field cannot be blank.' | trans }}</p>
</div>
<div class="uk-width-1-4">
<span class = "uk-align-right"> <button class = "uk-button" @click = "add | valid">{{ 'Add' | trans }}</button></span>
</div>
</div>
</form>
这是Vue-Source:
$(function () {
var vm = new Vue({
el: '#settings',
data: {
config: $data.config,
roles: $data.roles,
countries: $data.countries,
newTax: {
countrycode: '',
companies: '',
individuals: ''
}
},
methods: {
add: function (e) {
e.preventDefault();
if (!this.newTax) return;
this.config.vat.push({
countrycode: this.newTax.countrycode,
companies: this.newTax.companies,
individuals: this.newTax.individuals,
});
this.newTax = '';
},
remove: function (vat) {
this.config.vat.$remove(vat);
},
save: function () {
console.log(this.config.vat);
this.$http.post('admin/app/save', {entries: this.config}, function () {
this.$notify('Settings saved.');
}, function (data) {
this.$notify(data, 'danger');
}
);
},
vatMatch: function (code) {
return this.config.vat.filter(function (vat) {
return vat.countrycode == code;
}).length > 0;
}
}
});
});
这已经可以了 - 但是如果我选择一个国家并将税收字段留空并点击&#34;添加&#34;再次,第一个字段填充&#34; 0&#34;并在第二次点击后,第二个字段填充&#34; 0&#34;并且添加按钮有效。为什么验证规则设置&#34; 0&#34;如果验证失败? 我创建了一个小gif来演示我的意思:http://d.pr/eRbM
答案 0 :(得分:1)
问题在于你的add方法。使用newTax
验证if (!this.newTax)
对象时,它将返回true。即使对象属性为空,也存在该对象。创造意外行为。
您应该验证所需的每个属性,例如,如果您需要countrycode
和companies
,请将验证更改为:
if (!this.newTax.countrycode || !this.newTax.companies) return;
此外,尝试重置nexTax
对象时出现问题。你需要传入一个干净的对象,但是你用一个空的字符串重新分配它。
请尝试使用此方法,添加方法:
add: function (e) {
e.preventDefault();
if (!this.newTax.countrycode || !this.newTax.companies || !this.newTax.indiduals) return;
this.config.vat.push({
countrycode: this.newTax.countrycode,
companies: this.newTax.companies,
individuals: this.newTax.individuals,
);
this.newTax = {
contrycode = '',
companies = '',
individuals = ''
};
}