The can/map/validations plugin provides validations on maps. Validations
are set on can.Map's staticinit function.
The following validates the birthday attribute in Contacts:
Contact = can.Map.extend({
init : function(){
// validates that birthday is in the future
this.validate("birthday",function(birthday){
if(birthday > new Date){
return "your birthday needs to be in the past"
}
})
}
},{});
var contact = new Contact({birthday: new Date(2012,0) })
Use errors( [attrs...], newVal ) to read errors
or to test if setting a value would create an error:
// Check if there are errors on the instance
contact.errors() //-> null - there are no errors
// Test if setting birthday to new Date(3013,0) would error
contact.errors("birthday",
new Date(3013,0) )
//-> ["your birthday needs to be in the past"]
// Set birthday anyway
contact.attr("birthday", new Date(3013,0) )
// Get all errors
contact.errors()
//-> {
// birthday: ["your birthday needs to be in the past"]
// }
// Get errors for birthday
contact.errors("birthday")
//-> ["your birthday needs to be in the past"]
can.Map.validateRangeOf(attrNames, low, hi, [options]) Attributes are in the given numeric range.
Error Method
can.Map.errors() runs the validations on this model. You can also pass it an array
of attributes to run only those attributes. It returns
nothing if there are no errors, or an object of errors by attribute.
To use validations, it's required you use the map/validations plugin.
Task = can.Map.extend({
init : function(){
this.validatePresenceOf("dueDate")
}
},{});
var task = new Task(),
errors = task.errors()
errors.dueDate[0] //-> "can't be empty"
The following validates the
birthday
attribute in Contacts:Use errors
( [attrs...], newVal )
to read errors or to test if setting a value would create an error:Validation Methods
The most basic validate method is validate
()
.There are several built-in validation methods so you don't have to define your own in all cases like in the birthday example above.
(attrNames, options, proc)
Attributes validated with function.(attrNames, regexp, options)
Attributes match the regular expression.( attrNames, inArray, [options] )
Attributes are available in a particular array.(attrNames, min, max, [options])
Attributes' lengths are in the given range.( attrNames, [options] )
Attributes are not blank.(attrNames, low, hi, [options])
Attributes are in the given numeric range.Error Method
can.Map.errors
()
runs the validations on this model. You can also pass it an array of attributes to run only those attributes. It returns nothing if there are no errors, or an object of errors by attribute.To use validations, it's required you use the map/validations plugin.
Listening to events
Use bind to listen to error messages:
Demo
Click a person's name to update their birthday. If you put the date in the future, say the year 2525, it will report back an error.