Form validation before Submit

21,069

Solution 1

I am using javascript to do the validations. Following is the form code:

<form action="upload.php" method="post" onSubmit="return validateForm()">
    <input type="text" id="username">
    <input type="text" password="password">
    <input type="submit" value='Login' name='login'>
</form>

To perform validation write a javascript function:

<script>
  function checkform(){
    var uname= document.getElementById("username").value.trim().toUpperCase();

    if(uname=== '' || uname=== null) {
      alert("Username is blank");
      document.getElementById("username").backgroundColor = "#ff6666";
      return false;
    }else document.getElementById("username").backgroundColor = "white";

    var pass= document.getElementById("password").value.trim().toUpperCase();

    if(pass=== '' || pass=== null) {
       alert("Password is blank");
       document.getElementById("password").backgroundColor = "#ff6666";
       return false;
     }else document.getElementById("password").backgroundColor = "white";

    return true;
  }
</script>

Solution 2

You are using,

<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
       Add Walk In Patient
</button>

Here, submit button is used for submitting a form and will never trigger click event. Because, submit will be triggered first thus causing the click event skip.

$('#add_walkin_patient_button').on('click', function (e) {

This would have worked if you have used normal button instead of submit button

<input type="button">Submit</button>

Now to the problem. There are two solution for it ,

If you use click event, then you should manually trigger submit on correct validation case,

<input type="button" id="add_walkin_patient_button">Submit</button>
//JS : 
$("#add_walkin_patient_button").click(function() {
   if(valid){
     $("#form-id").submit();
    }

Another option is to use submit event;which is triggered just after you click submit button. Here you need to either allow form submit or halt it based on your validation criteria,

$("#form-id").submit(function(){
   if(invalid){
     //Suppress form submit
      return false;
   }else{
      return true;
   }
});

P.S

And i would recommend you to use jQuery Validate as suggested by @sherin-mathew

Solution 3

make a javascript validation method (say, validateForm(), with bool return type). add [onsubmit="return validateForm()"] attribute to your form and you are done.

Share:
21,069
H Dindi
Author by

H Dindi

BY DAY : Systems Developer at mHealth Kenya Ltd BY NIGHT : Code Machine ,book junkie ,Zombie FOR FUN : Explore the Great rift valley , Aspiring farmer , Social Entrepreneurs enthusiast.

Updated on August 11, 2020

Comments

  • H Dindi
    H Dindi almost 4 years

    I have the following form that needs to feed into the database but I would like it to be validated before it can be saved into the database :

    <form name="add_walkin_patient_form" class="add_walkin_patient_form" id="add_walkin_patient_form"  autocomplete="off" >
    
                    <div class="form-line">
    
                        <div class="control-group">
                            <label class="control-label">
                                Patient Name
                            </label>
                            <div class="controls">
                                <input type="text" name="patientname" id="patientname" required="" value=""/>
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">
                                Patient Phone Number
                            </label>
                            <div class="controls">
                                <input type="text" name="patient_phone" id="patient_phone" required="" value=""/>
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">
                                Department
                            </label>
                            <div class="controls">
                                <select name="department" required="" class="department" id="department">
                                    <option value="">Please select : </option>
                                    <option value="Pharmacy">Pharmacy</option>
                                    <option value="Laboratory">Laboratory</option>
                                    <option value="Nurse">Nurse</option>
    
                                </select>
                            </div>
                        </div>
                    </div>
    
                    <button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
                        Add Walk In Patient
                    </button>
                </form>
    

    And the submit is done by a jquery script using the following script :

    <script type="text/javascript">
    
        $(document).ready(function () {
            //delegated submit handlers for the forms inside the table
            $('#add_walkin_patient_button').on('click', function (e) {
                e.preventDefault();
    
                //read the form data ans submit it to someurl
                $.post('<?php echo base_url() ?>index.php/reception/add_walkin', $('#add_walkin_patient_form').serialize(), function () {
                    //success do something
    
                    // $.notify("New Patient Added Succesfully", "success",{ position:"left" });
                    $(".add_walkin_patient_form").notify(
                            "New Walkin Patient Added Successfully",
                            "success",
                            {position: "center"}
                    );
                    setInterval(function () {
                        var url = "<?php echo base_url() ?>index.php/reception/";
                        $(location).attr('href', url);
                    }, 3000);
    
    
                }).fail(function () {
                    //error do something
                    $(".add_walkin_patient_form").notify(
                            "There was an error please try again later or  contact the system support desk  for assistance",
                            "error",
                            {position: "center"}
                    );
    
                })
            })
    
        });
    
    </script>
    

    How can I put form validation to check if input is empty before submitting it into the script?

  • Jeremy Caney
    Jeremy Caney almost 4 years
    Please don’t just dump a huge block of code as an answer without any explanation. What is this doing? What specifically addresses the OP’s question? And, as this is an old question with four existing answers, how does it vary from those answers? Review the existing answers to get an idea of how to present answers here on Stack Overflow.