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

后端 未结 3 817
挽巷
挽巷 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: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.

提交回复
热议问题