Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #### forms.py #####
- #This form is a one-field form with the sole purpose of validating the email.
- class EmailValidationForm (forms.Form):
- reg_email = forms.EmailField()
- def __init__(self, *args, **kwargs):
- super(EmailValidationForm, self).__init__(*args, **kwargs)
- self.fields['reg_email'].required = True
- def clean(self):
- existing_user = User.objects.filter(email=self.cleaned_data['reg_email']).first()
- if existing_user != None:
- raise forms.ValidationError("This e-mail is already in use.")
- return self.cleaned_data
- #### views.py #####
- #The page with the form
- def show_form (request, template="my_form.html"):
- form = EmailValidationForm ()
- return render(request, template, locals())
- #The view to validate the e-mail
- def validate_user_email (request):
- form = EmailValidationForm(data=request.POST)
- if form.is_valid():
- return JsonResponse({
- 'status': 'ok',
- 'html': '',
- })
- else:
- return JsonResponse({
- 'status': 'errors',
- 'html': render_to_string('ajax_form_errors.html', locals())
- })
- #### HTML my_form.html #####
- <form class="form" method="POST" action="#" id="email_validation_form">
- <label>{{ form.reg_email.label }}</label>
- {{ form.reg_email }}
- <div id="form_errors_wrapper"></div>
- </form>
- #### HTML - ajax_form_errors.html ####
- {% if form.errors %}
- {% for field in form %}
- {% for error in field.errors %}
- <div class="alert alert-danger">
- <strong>{{ field.label }} - {{ error|escape }}</strong>
- </div>
- {% endfor %}
- {% endfor %}
- {% for error in form.non_field_errors %}
- <div class="alert alert-danger">
- <strong>{{ error|escape }}</strong>
- </div>
- {% endfor %}
- {% endif %}
- #### Javascript #####
- <script>
- function validate_user_email () {
- $.ajax({
- async: true,
- type: "POST",
- beforeSend: function (request)
- {
- request.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); //this adds the CSRF token in the ajax call
- },
- url: "{% url 'validate_user_email' %}",
- data: $('#email_validation_form').serialize(),
- dataType: 'json',
- contentType: "application/x-www-form-urlencoded;charset=UTF-8",
- success: function(data){
- //No form errors.. all good
- if (data.status == "ok") {
- $('#form_errors_wrapper').html('');
- //The e-mail is invalid.. show the errors.
- } else {
- $('#form_errors_wrapper').html(data.html);
- }
- },
- complete: function () {
- },
- error: function(XMLHttpRequest, textStatus, errorThrown) {
- alert('server error');
- }
- });
- }
- //Since a simple keyup listener will trigger the validation at every keystroke, you can do something like this to only check after 300ms of the last keystroke.
- var search_timeout = undefined;
- $(function(){
- $('#id_reg_email').keyup(function() {
- if(search_timeout != undefined) {
- clearTimeout(search_timeout);
- }
- search_timeout = setTimeout(function() {
- search_timeout = undefined;
- validate_user_email();
- }, 300);
- });
- });
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement