0

I am practicing AJAX in django template project, i have a signup form where i have 4 fields to submit,i'm using signup button feature to implement ajax function,its working fine, but problem is when i am keeping form empty and hitting the button its also submitting, so how can i validate fields that when there would be no values given it would show error msg to fill up all fields? Thnaks in advance.

    <script>
    $(document).ready(function(){
         $('#signup-btn').click(function(event){
            console.log('hi-signup')

            $.ajax({
                method: "POST",
                url: '/register',
                data: {
                    name :$('#id_fullname').val(),
                    email : $('#id_email').val(),
                    country : $('#id_country').val(),
                    password : $('#id_password').val(),
                    csrfmiddlewaretoken:'{{ csrf_token }}',

                },

                success: function(res) {
                var response = $.parseJSON(res)
                $('.signup-data').html(response.msg)
                          if (response.code == 200) {
                            $('.signup-data').html(response.msg);
                            window.location = "http://localhost:8000";
                        }
                        },
            })

        })

    })
</script>

html

  <form  class="my-signup-form" action="/register" method="post">
                                  {% csrf_token %}
                                  <div class="signup-data"></div>
                                  <div class="top-row">
                                    <div class="field-wrap">
                                      <input name="signup-fullname" id="id_fullname" type="text" required autocomplete="off" placeholder="Full Name"/>
                                    </div>

                                    <div class="field-wrap">
                                      <input name="signup-email" id="id_email" type="text"required autocomplete="off" placeholder="Email ID"/>
                                    </div>
                                  </div>

                                  <div class="field-wrap select2">
                                    <span class="select-arrow"></span>
                                    <select name="signup-country" id="id_country" class="selextbox">
                                     <option value="" selected disabled>Select your country</option>
                                    <option value="United States">United States</option>
                                    <option value="United Kingdom">United Kingdom</option>
                                    <option value="Afghanistan">Afghanistan</option>

                                </select>
                                  </div>


                                  <div class="field-wrap">
                                    <input name="signup-password" id="id_password" type="password"required autocomplete="off" placeholder="Password"/>
                                  </div>
                                  <p class="charcters">Minimum 8 Charcters</p>

                                  <button id="signup-btn" type="button" class="button button-block"/>Get Started</button>

                              </form>
1
  • If you want no submission in case of invalid entries you need to do this in javascript and this does not have anything todo with ajax or django. You could also use the jquery validation plugin (jqueryvalidation.org). Commented Sep 16, 2018 at 14:30

2 Answers 2

2
<script>
            $('#signup-btn').click(function(event){
                if(validate()){
                    $.ajax({
                        method: "POST",
                        url: '/register',
                        data: {
                            name :$('#id_fullname').val(),
                            email : $('#id_email').val(),
                            country : $('#id_country').val(),
                            password : $('#id_password').val(),
                            csrfmiddlewaretoken:'{{ csrf_token }}',

                        },
                        success: function(res) {
                            var response = $.parseJSON(res)
                            $('.signup-data').html(response.msg)
                                  if (response.code == 200) {
                                  $('.signup-data').html(response.msg);
                                  window.location = "http://localhost:8000";
                            }
                         },
                    })

                  })
                }

            })

            function validate(){

                var isValid = true;
                if (!$('#id_fullname').val()){
                    isValid = false
                }
                if (!$('#id_email').val()){
                    isValid = false
                }else{
                   if(!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($('#id_email').val()))){
                        isValid = false; 
                    }
                }
                if (!$('#id_country').val()){
                    isValid = false
                }
                if (!$('#id_password').val()){
                    isValid = false
                }
                return isValid;
            }
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

Sir,you are great! i was struggling to implement such ,so can i add validation for email is in [email protected] format or not?
updated the validation function, please check for email format validation
so sir thanks a lot, it stopped form submission but is there any way i can show message to fill all the filed?
so i added in every function $('.signup-data').html('error message') to show it to user, thanks a lot for helping me sir
1

I remember this is what i did before in one of my app try:

$(document).ready(function(){

$('#signup-btn').click(function(){

    formValidate();   

     console.log('hi-signup')

            $.ajax({
                method: "POST",
                url: '/register',
                data: {
                    name :$('#id_fullname').val(),
                    email : $('#id_email').val(),
                    country : $('#id_country').val(),
                    password : $('#id_password').val(),
                    csrfmiddlewaretoken:'{{ csrf_token }}',

                },

                success: function(res) {
                var response = $.parseJSON(res)
                $('.signup-data').html(response.msg)
                          if (response.code == 200) {
                            $('.signup-data').html(response.msg);
                            window.location = "http://localhost:8000";
                        }
                        },
            })

        })

function formValidate(){

    var name = $('#id_fullname').val();
    var email = $('#id_email').val();

    var country = $('#id_country').val();
    var password = $('#id_password').val();

    var nameReg = /^[A-Za-z]+$/;
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var inputValue = new Array(name, email, country, password);

    var inputMessage = new Array("name", "email", "country", "password");

     $('.error-message').hide();

        if(inputValue[0] == ""){
            $('#id_fullname').after('<span class="error-message"> Please enter your ' + inputMessage[0] + '</span>');
        } 
        else if(!nameReg.test(name)){
            $('#id_fullname').after('<span class="error-message"> Letters only</span>');
        }

        if(inputVal[1] == ""){
            $('#id_email').after('<span class="error-message"> Please enter your ' + inputMessage[1] + '</span>');
        } 
        else if(!emailReg.test(email)){
            $('#id_email').after('<span class="error-message"> Please enter a valid email address</span>');
        }

        if(inputVal[2] == ""){
            $('#id_country').after('<span class="error-message"> Please enter your ' + inputMessage[2] + '</span>');
        } 

        if(inputVal[3] == ""){
            $('#id_password').after('<span class="error-message"> Please enter your ' + inputMessage[3] + '</span>');
        }       
}   

});

4 Comments

thanks a lot, its a very detailed answer, i was thinking to expanding my validation and this answer fits perfect..
hi, can you please tell me where did you put that $('.error-message').hide() div?in html
on the <span class="error-message"> if the condition is true error message will pop up
thanks mate,so how you add code to check password length and is it having one speacial character and one digit or not?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.