How can I make a Django form field contain only alphanumeric characters

后端 未结 3 811
挽巷
挽巷 2020-12-08 07:09

I have this model

name = models.CharField(max_length=50, blank=True, null=True)
email = models.EmailField(max_length=50, unique=True)

I wa

相关标签:
3条回答
  • 2020-12-08 07:27

    Instead of RegexValidator, give validation in forms attributes only like...

            class StaffDetailsForm(forms.ModelForm):
                 first_name = forms.CharField(required=True,widget=forms.TextInput(attrs={'class':'form-control' , 'autocomplete': 'off','pattern':'[A-Za-z ]+', 'title':'Enter Characters Only '}))
    

    and so on...

    Else you will have to handle the error in views. It worked for me try this simple method... This will allow users to enter only Alphabets and Spaces only

    0 讨论(0)
  • 2020-12-08 07:33

    That is little bit wider than you want, but you also can use SlugField:

    A Slug is basically a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. For example, in a typical blog entry URL: https://www.geeksforgeeks.org/add-the-slug-field-inside-django-model/

    field_name = models.SlugField(max_length=200, **options)
    
    0 讨论(0)
  • 2020-12-08 07:36

    You would use a validator to limit what the field accepts. A RegexValidator would do the trick here:

    from django.core.validators import RegexValidator
    
    alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.')
    
    name = models.CharField(max_length=50, blank=True, null=True, validators=[alphanumeric])
    email = models.EmailField(max_length=50, unique=True, validators=[alphanumeric])
    

    Note that there already is a validate_email validator that'll validate email addresses for you; the alphanumeric validator above will not allow for valid email addresses.

    0 讨论(0)
提交回复
热议问题