Create a new url to for a the view function which will validate the input.
path('ajax/validate_input/', views.ValidateInput.as_view(), name='my_ajax_url'),
In views.py do your validation then return a JsonResponse.
from django.views import View
from django.http import JsonResponse
class ValidateInput(View):
def post(self, request):
# Do validation
return JsonResponse({
'valid': True,
'message': 'Invalid Characters',
})
Now in your template write js code that will make ajax requests to that url.
According to received response make changes to your webpage using js in the success of your ajax.
// add jQuery
// put the code below inside an event handle, maybe on input change
$.ajax({
url: {% url 'my_ajax_url' %},
method: 'POST',
data: {
body: body,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
dataType: 'json',
success: function(data){
console.log(data.valid);
console.log(data.message);
// do stuff to change your webpage here
}
});
I would recommend validating input on input change, but if you want to do it in from submit, then add an event handler for form submit. There use event.preventDeafault to prevent form submit, then do the ajax stuff, and according to the received json do something else. Maybe if valid = true then proceed further or if valid = false then show the message received in json below the input box.