newforms
newforms copied to clipboard
Adding an error to a specific field in cross-field cleaning leads to unexpected behaviour
Example:
var SignupForm = forms.Form.extend({
password: forms.CharField({widget: forms.PasswordInput}),
confirm: forms.CharField({widget: forms.PasswordInput})
clean: ['password', 'confirm', function() {
var {password, confirm} = this.cleanedData
if (password && confirm && password != confirm) {
this.addError('confirm', 'Does not match the entered password.')
}
}]
})
If you type a password, type a mis-matching confirmation of it, then change the password to match the confirmation, onChange validation will not clear the error which has been added to the confirm field, as addError() removed its data from cleanedData and the user hasn't interacted with the field again.
You could use form.data instead to mitigate this, but then you can't make use of the type coerced value which would have been present in cleanedData for things like data and numeric fields, e.g:
var ReleaseForm = LayoutForm.extend({
startDate: forms.DateField(),
endDate: forms.DateField(),
clean: ['startDate', 'endDate', function() {
var {startDate, endDate} = this.cleanedData
if (startDate && endDate && startDate > endDate) {
this.addError('endDate', 'Cannot be prior to Start Date.')
}
}]
})