'Only accept 2 digits integer array in django model form

How to make a form field that accept 2 digit numeric array in frontend. if someone enter more then 2 digit or string then The input value is automatically validated to ensure it is a properly formatted 2 digit integer array.

right

enter image description here

wrong below

enter image description here

i want validation like this:

enter image description here

My work

models.py

class Jodi(models.Model):
  numb = ArrayField(models.IntegerField(null=True, blank=True), null=True, blank=True)

forms.py

from django import forms
from .models import Jodi
class MyModelForm(forms.ModelForm):
    class Meta:
        model = Jodi
        fields = ['numb',]

views.py

if request.method=='POST':
        fm = MyModelForm(request.POST)
        if fm.is_valid():
            numbers = fm.cleaned_data['numb']
            numbers1 = []
            for x in numbers:
                if x:
                    numbers1.append(x)
            X=Jodi.objects.create(numb=numbers1,)
            X.save()
else:
    fm = MyModelForm()
    return render(request,'myapp/home.html',{'form':fm})

home.html

<form action="" method="post">{% csrf_token %}
        
      {{ form.as_p }}
        


Solution 1:[1]

Make use of widget and attrs to set a pattern to form field.

Use pattern ([0-9]{2})(,\s*[0-9]{2})* to have spaces after comma OR Use ([0-9]{2})(,[0-9]{2})* to have no spaces after comma.

Using widget:

class MyModelForm(forms.ModelForm):
    # code
    numb = forms.CharField(required=True,widget=forms.TextInput(attrs={'pattern':'([0-9]{2})(,[0-9]{2})*',}))
    # code

Sample pattern in action:

<html !doctype>    
    <body>
        <form action="" method="get">  
            <label for="number_array">Number Array: </label>  
            <input type="text" 
               placeholder="00,11,22"  
               pattern="([0-9]{2})(,\s*[0-9]{2})*"  
               autofocus  
               required>  
            <button>Go </button>  
        </form> 
    </body>
</html>

Solution 2:[2]

if fm.is_valid():
    numbers = fm.cleaned_data['numb']
    for n in numbers.split(','):
        if not n.isdigit() or len(n)!=2:
            # return render new form with error of not a valid input, input should be 2 digits numbers seprated by comma
    X=Jodi.objects.create(numb=numbers1,)
    X.save()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Achuth Varghese
Solution 2 Rajeel Rajput