| 1742 | |
| 1743 | def test_multivalue_field_validation(self): |
| 1744 | def bad_names(value): |
| 1745 | if value == 'bad value': |
| 1746 | raise ValidationError('bad value not allowed') |
| 1747 | |
| 1748 | class NameField(MultiValueField): |
| 1749 | def __init__(self, fields=(), *args, **kwargs): |
| 1750 | fields = (CharField(label='First name', max_length=10), |
| 1751 | CharField(label='Last name', max_length=10)) |
| 1752 | MultiValueField.__init__(self, fields=fields, *args, **kwargs) |
| 1753 | |
| 1754 | def compress(self, data_list): |
| 1755 | return ' '.join(data_list) |
| 1756 | |
| 1757 | class NameForm(Form): |
| 1758 | name = NameField(validators=[bad_names]) |
| 1759 | |
| 1760 | form = NameForm(data={'name' : ['bad', 'value']}) |
| 1761 | form.full_clean() |
| 1762 | self.assertFalse(form.is_valid()) |
| 1763 | self.assertEqual(form.errors, {'name': [u'bad value not allowed']}) |
| 1764 | form = NameForm(data={'name' : ['should be overly', 'long for the field names']}) |
| 1765 | self.assertFalse(form.is_valid()) |
| 1766 | self.assertEqual(form.errors, {'name': [u'Ensure this value has at most 10 characters (it has 16).', |
| 1767 | u'Ensure this value has at most 10 characters (it has 24).']}) |
| 1768 | form = NameForm(data={'name' : ['fname', 'lname']}) |
| 1769 | self.assertTrue(form.is_valid()) |
| 1770 | self.assertEqual(form.cleaned_data, {'name' : 'fname lname'}) |