djangocustom-validators

How to make Django validators dynamic?


I am new to Django. I am taking over a Django project developed by someone else. They took the basic form validators from here:

https://docs.djangoproject.com/en/2.0/topics/auth/passwords/

So if I open

settings/common.py

I see:

AUTH_PASSWORD_VALIDATORS = [
{
    'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    'OPTIONS': {
        'min_length': 9,
    }
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

My project manager is telling me that she wants these validators to happen while a person is typing, rather than when the form is submit. So I need to somehow make these validators trigger onBlur as the cursor leaves each field.

How is this done in Django?


Solution

  • This is not the right approach. Django is backend framework. This means it works as http server: you send a request and you get the response.

    What you probably wanted was to trigger request at each js event. This means you need to send ajax event to some validation endpoint (you would need to write Django method returning True or False) and call it for each js event. I'd rather suggest you another approach:

    Write js validator which would be called for each js event. This won't end up as DDoS and it will be much faster and lighter.

    var validate = function(text) {
      return text.length > 8; // or ajax sending text to validate
    }
    
    $('input.pass').on('input', function() {
      if (!validate($(this).val())) {
        $(this).addClass('error');
        $('p.error-msg').show();
      }
      else {
      	$(this).removeClass('error');
        $('p.error-msg').hide();
      }
    })
    input.pass.error {
      border: 1px solid #FF0000;
    }
    
    p.error-msg {
      color: #FF0000;
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input type="password" class="pass" />
    <p class="error-msg">
    Too short password.
    </p>