[英]Selectively validate model attributes using Backbone Validation plugin?
我正在使用Backbone Validation 插件並希望在不同時間有選擇地驗證不同的模型屬性集,這可能嗎?
我的測試模型對name
、 age
和address
進行了驗證,如果我只想驗證address
,我該怎么做?
我認為這是調用this.model.validate('address');
但所有驗證規則似乎都在運行?
JS
console.clear();
const Model = Backbone.Model.extend({
validation: {
name: {
required: true
},
age: {
range: [1, 80],
required: true
},
address: {
minLength: 1,
msg: 'Address required',
required: false
}
}
});
const View = Backbone.View.extend({
template: Handlebars.compile( $('.tmpl-person').html() ),
className: 'view',
events: {
'click .js-action--validate-keys': 'actionValidateKeysClicked',
'click .js-action--validate-key': 'actionValidateKeyClicked'
},
initialize() {
Backbone.Validation.bind(this);
this.listenTo(this.model, 'validated', this.onModelValidated, this);
this.listenTo(this.model, 'validated:valid', this.onModelValid, this);
this.listenTo(this.model, 'validated:invalid', this.onModelInvalid, this);
},
render() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
actionValidateKeysClicked(event) {
event.preventDefault();
console.log('actionValidateKeysClicked');
this.model.set({
'name': 'Joe Bloggs',
'age': 23
});
this.model.validate(['name', 'age']);
},
actionValidateKeyClicked(event) {
event.preventDefault();
console.log('actionValidateKeyClicked');
this.model.set('address', '123 ABC');
this.model.validate('address');
},
/**
* The validated event is triggered after validation is performed, either it was successful or not.
* isValid is true or false depending on the result of the validation.
*/
onModelValidated(isValid, model, errors) {
console.log('onModelValidated', isValid, model, errors);
},
onModelValid(model) {
console.log('onModelValid', model);
},
onModelInvalid(model, errors) {
console.log('onModelInvalid', model, errors);
}
});
const newModel = new Model();
const newView = new View({
model: newModel
});
document.body.append(newView.render().el);
JSfiddle http://jsfiddle.net/kyllle/qmx2y9yr/
isValid
為了僅驗證某些字段, Backbone.Validation提供了isValid
的修改版本。
如果您傳遞屬性的名稱或名稱數組,則可以檢查屬性是否有效:
// Check if name is valid var isValid = model.isValid('name'); // Check if name and age are valid var isValid = model.isValid(['name', 'age']);
isValid
僅在驗證出現錯誤時才會觸發'invalid'
事件( source ),並且不會觸發'validated'
事件或'validated:valid'
。
preValidate
有時檢查(例如在每次按鍵時)輸入是否有效 - 無需更改模型 - 以執行某種實時驗證可能很有用。 您可以通過調用
preValidate
方法並將屬性的名稱和要驗證的值或屬性的散列傳遞給它來執行屬性的一組驗證器或屬性的散列。如果該值無效,則返回錯誤消息(真實),否則返回假值。
// Validate one attribute // The `errorsMessage` returned is a string var errorMessage = model.preValidate('attributeName', 'Value'); // Validate a hash of attributes // The errors object returned is a key/value pair of attribute name/error, eg // { // name: 'Name is required', // email: 'Email must be a valid email' // } var errors = model.preValidate({name: 'value', email: 'foo@example.com'});
我拿了你的代碼並在下面做了一個小例子來證明使用isValid
時不會觸發 invalid 事件,但使用validate
時會觸發它。 另請注意, preValidate
不會觸發任何事件。
const Model = Backbone.Model.extend({ validation: { name: { required: true }, age: { range: [1, 80], required: true }, address: { minLength: 1, msg: 'Address required', required: true } } }); const View = Backbone.View.extend({ template: $('.tmpl-person').html(), className: 'view', events: { 'click .validate': 'onValidateClick', 'click .is-valid': 'onIsValidClick', 'click .pre-validate': 'onPreValidateClick', }, initialize() { Backbone.Validation.bind(this); this.listenTo(this.model, { 'all': this.onAllModelEvent, // 'validated': this.onModelValidated, // 'validated:valid': this.onModelValid, // 'validated:invalid': this.onModelInvalid }); }, render() { this.$el.html(this.template); this.$checkbox = this.$('.invalid'); return this; }, getAddress() { return this.$checkbox.is(':checked') ? null : '123 ABC'; }, onValidateClick() { console.log('validate click'); this.model.set('address', this.getAddress()); console.log("validate:", this.model.validate('address')); }, onIsValidClick() { console.log('isValid click'); this.model.set('address', this.getAddress()); console.log("isValid:", this.model.isValid('address')); }, onPreValidateClick() { console.log('preValidate click'); this.model.set('address', this.getAddress()); console.log("preValidate:", this.model.preValidate('address')); }, onAllModelEvent: function(event) { console.log("event:", event); } }); const newModel = new Model(); const newView = new View({ model: newModel }); document.body.append(newView.render().el);
* { -webkit-font-smoothing: antialiased; } body { padding: 5%; font-size: 16px; line-height: 1.4; } .view { width: 100%; height: 100vh; background: lightBlue; } .btn { outline: none; border: none; background: #1C90F3; border-radius: 4px; color: white; padding: 15px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.validation/0.11.5/backbone-validation-min.js"></script> <script type="text/template" class="tmpl-person"> Set 'address' and use: <button type="button" class="btn validate">validate</button> <button type="button" class="btn is-valid">isValid</button> <button type="button" class="btn pre-validate">preValidate</button> <br> <input type="checkbox" class="invalid">make address invalid. </script>
請注意我如何將listenTo
與對象listenTo
使用,而不是調用它 3 次。
this.listenTo(this.model, {
'validated': this.onModelValidated,
'validated:valid': this.onModelValid,
'validated:invalid': this.onModelInvalid
});
此外,沒有this
參數傳遞給listenTo
,這可能與舊的on
/ bind
語法混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.