var SignupForm = form.Form.extend({
username: forms.CharField(),
/**
* @param {function(err, field, errorMessages)} cb
*/
cleanUsernameAsync: function(cb) {
// Return false to indicate that no async validation is being performed -
// this shouldn't be strictly needed for field-specific custom cleaning
// methods, as they will only be called if the field is valid according to
// Field validation and clean<Name> validation, BUT you could take advantage
// of this to combine sync & async validation into the same custom clean
// method, calling addError and returning false or throwing a ValidationError
// before the synchronous part.
This means we don't need a separate clean<Name>Async(cb)
method for this - we can just change the definition for the existing method from clean<Name>()
to clean<Name>([cb])
and check its arity!
if (!this.cleanedData.username) {
return false
}
// Kick async processing off
var req = superagent.post('/checkusername').send({username: username}).end(
function(res) {
// Callback with an Error if things went wrong with the call
if (!res.ok) {
return cb(new Error(res.txt))
}
// If something is invalid based on the response, callback with arguments
// for addError().
if (!res.body.available) {
return cb(null, 'username', 'This username is already taken.')
}
cb(null)
}
)
// Return an object with .onCancel() for pending stuff to be aborted
return {
onCancel: req.abort.bind(req)
}
}
})