2

I have created a simple form in HTML that submits data to Microsoft CDS using javascript. The form submits fine.

I wanted to put in some validation to ensure that fields must be completed (no empty fields) so I used javascript form validation. I have only done validation on the first two fields: Title and First Name.

The validation works to the extent that a message pops up saying "The title must not be empty" and "The first name must not be empty" - BUT... the form still submits!

I think the problem is that I'm using two separate Scripts, one to run the validation and one to submit the data. How do I combine the two?

<!DOCTYPE html>
<html>
    <head>
        <title>Contact Us</title>
        
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf-8" />
        
        <! -- JQUERY LINK -->
        <script src="jq.min.js"></script>

        <style>
            body {font-family: Arial, Helvetica, sans-serif;}
            * {box-sizing: border-box;}

            input, select, textarea {
              width: 100%;
              padding: 12px;
              border: 1px solid #ccc;
              border-radius: 4px;
              box-sizing: border-box;
              margin-top: 6px;
              margin-bottom: 16px;
              resize: vertical;
            }

            button {
              background-color: #04AA6D;
              color: white;
              padding: 12px 20px;
              border: none;
              border-radius: 4px;
              cursor: pointer;
            }

            button:hover {
              background-color: #45a049;
            }

            .container {
              border-radius: 5px;
              background-color: #f2f2f2;
              padding: 20px;
            }
        </style>
    </head>
    <body>
        <script>
            function validateform(){  
            var title=document.myform.Title.value;  
            var firstname=document.myform.FirstName.value;  
              
            if (title==null || title==""){  
              alert("Title can't be blank");  
              return false;  
            }else if (firstname==null || firstname==""){  
              alert("Firstname can't be blank.");  
              return false;  
              }  
            }  
        </script> 
    
        <h3>Contact Form to submit to SP List</h3>

        <! -- HTML FORM BELOW -->
        <div class="container">
            <form name="myform" onsubmit="return validateform()">
            <! -- HTML INPUT -->
            <label>Title</label>
            <input type="text" id="Title" placeholder="Your title...">
          
            <label>First Name</label>
            <input type="text" id="FirstName" placeholder="Your forename..">

            <label>Last Name</label>
            <input type="text" id="LastName" placeholder="Your surname..">
            
            <label>Date</label><br>
            <input type="date" id="Date" placeholder="Your surname..">  
            
            <label>Country</label>
            <select id="Country">
              <option value="England">England</option>
              <option value="Wales">Wales</option>
              <option value="Scotland">Scotland</option>
            </select>

            <label>Message</label>
            <textarea id="Message" placeholder="Write something.." style="height:200px"></textarea>

            <! -- HTML SUBMISSION -->
            <button id="btn_submit">Submit</button>
            <input id="postResult" type="text" value="Submission status: Awaiting submission" readonly>
            </form>
        </div>

        <! -- JS BELOW --> 
        <script>
            $(function () {
                $("#btn_submit").click(function () {
                    
                    var formData = { 
                        Title: $("#Title").val(), 
                        FirstName: $("#FirstName").val(), 
                        LastName: $("#LastName").val(),
                        Message: $("#Message").val(), 
                        Country: $("#Country").val(), 
                        Date: $("#Date").val() 
                    };
                    
                    $.ajax({
                    contentType: 'application/json',
                    type: "POST",
                        url: "XXXXXXXXXXXX",
                        data: JSON.stringify(formData),
                    success: function () {
                        $("#postResult").val("Submission status: Success");
                    },
                    error: function () {
                        $("#postResult").val("Submission status: Failed");
                    }
                });
                });
                
                
            });
        </script>
    </body>
</html>
0

3 Answers 3

2

This is happening because you are not using a submit button to submit the form, you are using a regular button that launches an AJAX POST when clicked, and you are trying to stop the form from submitting using onsubmit.

In order to not submit the form you either should use the default form POST with an input submit button, and return false to onsubmit. Or call the validation when the button is clicked and if it passes the validation then call the AJAX method. Don't call the AJAX method like $("#btn_submit").click(function ()) as this will happen and you cant prevent it once the user clicks the button, you should instead call the validation and with an if you either call the AJAX method or not.

With your code it would be like:

    <! -- JS BELOW --> 
    <script>
    
        function validateForm(){  
        var title=document.myform.Title.value;  
        var firstname=document.myform.FirstName.value;  
          
        if (title==null || title==""){  
          alert("Title can't be blank");  
          return false;  
        }else if (firstname==null || firstname==""){  
          alert("Firstname can't be blank.");  
          return false;  
        }else{
          return true;     
        }
        }  

    
        $(function () {
            $("#btn_submit").click(function () {
            
                if(validateForm()){
                
                var formData = { 
                    Title: $("#Title").val(), 
                    FirstName: $("#FirstName").val(), 
                    LastName: $("#LastName").val(),
                    Message: $("#Message").val(), 
                    Country: $("#Country").val(), 
                    Date: $("#Date").val() 
                };
                
                $.ajax({
                contentType: 'application/json',
                type: "POST",
                    url: "XXXXXXXXXXXX",
                    data: JSON.stringify(formData),
                success: function () {
                    $("#postResult").val("Submission status: Success");
                },
                error: function () {
                    $("#postResult").val("Submission status: Failed");
                }
            });
                }
            });
            
            
        });
    </script>
</body>
Sign up to request clarification or add additional context in comments.

2 Comments

"Or call the validation when the button is clicked and if it passes the validation then call the AJAX method." - how do I go about doing this?
@DrHY I updated my answer with the code as example. Check how firstly i put the code in the same <script> tag and then in the validation method I return true if it has no errors. Then in the function triggered by clicking the button there's an if(validateForm()) that will only submit the form if it returns true (has passed the validation)
1

Amend the validateform function as follow:

function validateform(){
  let invalid = false

  // Do the validation here. assign invalid to true if any field is invalid

  if (invalid) {
    window.event.preventDefault() // Prevent the default form submit behavior
  } else {
    // Your form submission ajax logic here...
  }
}

And remove the second script block since the logic has already been embedded into the above validateform function.

3 Comments

You don't need the preventDefault as it is not a form with a submit it is a button calling an AJAX POST request
The btn_submit button is inside a form element. The type of a button inside a form element is defaulted to submit which submit the form when click (type Doc).
Didn't know that the type of a button by default would be submit. Nice, thank you
0

You could remove the validadeteform() and put all logic into the callback function.

  • Remove onsubmit on your form. It should be like this:
<form name="myform">
  • Change button to input type, something like this:
<input type="button" id="btn_submit" value="Submit" />
  • The callback function called when you click #btn_submit should look like this:
$(function () {
                    $("#btn_submit").click(function () {

                        var formData = {
                            Title: $("#Title").val(),
                            FirstName: $("#FirstName").val(),
                            LastName: $("#LastName").val(),
                            Message: $("#Message").val(),
                            Country: $("#Country").val(),
                            Date: $("#Date").val()
                        };

                        if (formData.Title == "" || formData.FirstName == "") {
                            alert("Title and Firstname can't be blank");
                        } else {
                            $.ajax({
                                contentType: 'application/json',
                                type: "POST",
                                url: "XXXXXXXXXXXX",
                                data: JSON.stringify(formData),
                                success: function () {
                                    $("#postResult").val("Submission status: Success");
                                },
                                error: function () {
                                    $("#postResult").val("Submission status: Failed");
                                }
                            });
                        }
                    });
                });

Comments

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.