23π
β
First you need a regex validator:
Django validators / regex validator
Then, add it into the validator list of your field:
using validators in forms
Simple example below:
from django.core.validators import RegexValidator
my_validator = RegexValidator(r"A", "Your string should contain letter A in it.")
class MyForm(forms.Form):
subject = forms.CharField(
label="Test field",
required=True, # Note: validators are not run against empty fields
validators=[my_validator]
)
π€Art
1π
you could also ask from both part in your form, it would be cleaner for the user :
class CapaForm(forms.Form):
capa1 = forms.IntegerField(max_value=9999, required=False)
capa2 = forms.IntegerField(max_value=99, required=False)
and then just join them in your view :
capa = self.cleaned_data.get('capa1', None) + '-' + self.cleaned_data.get('capa2', None)
π€romainm
- Django query filter by number of ManyToMany objects
- Django-rest-framework : list parameters in URL
- Display user group in admin interface?
- Django ConnectionAbortedError + TypeError + AttributeError
1π
You can also use RegexField. Itβs the same as CharField
but with additional argument regex
. Under the hood it uses validators.
Example:
class MyForm(forms.Form):
field1 = forms.RegexField(regex=re.compile(r'\d{6}\-\d{2}'))
π€tvorog
- Django: Reading Array of JSON objects from QueryDict
- Django query filter by number of ManyToMany objects
- Reordering fields in Django model
- Perform a logical exclusive OR on a Django Q object
1π
Regex validator does not work for me in Django 2.2
Step to set up custom validation for a field value:
-
define the validation function:
def number_code_validator(value): if not re.compile(r'^\d{10}$').match(value): raise ValidationError('Enter Number Correctly')
-
In the form add the defined function to validators array of the field:
number= forms.CharField(label="Number", widget=TextInput(attrs={'type': 'number'}), validators=[number_code_validator])
π€smrf
- Using django how can I combine two queries from separate models into one query?
- After login the `rest-auth`, how to return more information?
- Django formset β show extra fields only when no initial data set?
Source:stackexchange.com