views:

427

answers:

3

In Django 1.0, what is the best way to catch and show an error if user enters only whitespace (" ") in a form field?

class Item(models.Model):
    description = models.CharField(max_length=100)

class ItemForm(ModelForm):
    class Meta:
        model = Item

if user enters only whitespace (" ") in description CharField, what change needs to done to class Item or class ItemForm so that form.is_valid() fails and shows an error?

After form.is_valid(), I could write the code to check for only whitespaces in description field and raise a validation error but there has to be a better way. Can RegexField be used to specify description entered should not be just whitespaces. Any suggestions?

+3  A: 
class ItemForm(forms.ModelForm):
    class Meta:
        model = Item

    def clean_description(self):
        if not self.cleaned_data['description'].strip():
            raise forms.ValidationError('Your error message here')

The forms validation documentation might provide a good read.

Carl Meyer
Ingenutrix
+1  A: 

Figured it out. Just adding description = forms.RegexField(regex=r'[^(\s+)]') to class ItemForm will cause the form.is_valid() to fail and show the error

class ItemForm(ModelForm):
    description = forms.RegexField(regex=r'[^(\s+)]')
    class Meta:
        model = Item

To include your own message, add error_message=... to forms.RegexField

description = forms.RegexField(regex=r'[^(\s+)]', error_message=_("Your error message here."))
Ingenutrix
+1  A: 

why regex? just use str.strip() to check if a string consists of only whitespace

hasen j