0

I have a form where user enter a cnic number if this number is less than 15 then alert a msg and stop the form submission but issue is that form submission cannot stop when the cnic number is less than 15.

<script>
    function validateform()
    {

        var cnic1 = document.getElementById("cnic1").value;
        if (cnic1.length < 15)
        {
            window.alert("Invalid CNIC");
            cnic1.focus();
            return false;
        }
    }
</script>

<form class="col s12" action="tabs.php" method="post" enctype="multipart/form-data" name="applyform">

    <div class="row">
        <div class="input-field col s1"></div>
        <div class="input-field col s4"><label>CNIC No. </label>
            <font style="color: #ff0000">*</font>
        </div>
        <div class="input-field col s6">
            <input id="cnic1" name="cnic1" type="text" value="<?php echo $RowAcc['cnic'];?>" maxlength="15" placeholder="CNIC #" required>
        </div>
    </div>
</form>

Is there issue in php submission code write on tabs.php page that's why form still submitting process?

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Ahil Khan
  • 227
  • 1
  • 4
  • 12

4 Answers4

7

You don't have to return false to stop the form from being submitted. You need to use the event's preventDefault() method, and submit the form using JS if the data is valid. Like this:

function validateform(e) { // take the event as parameter
    e.preventDefault(); // stop the submission

    var cnic1 = document.getElementById("cnic1");

    if (cnic1.value.length < 15) {
        window.alert("Invalid CNIC");
        cnic1.focus();
    } else {
        form.submit();
    }
}

var form = document.getElementsByName('applyform')[0];
form.addEventListener('submit', validateform);

I also added the listener using JS just so you can be sure the event parameter is passed to your validation function. Remove the onsubmit="..." from your form.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
0

Call the js function from onchange = "" event, or use any button and call click event. Your js function will work.

-1
return false; 

or

event.preventDefault();
splattne
  • 102,760
  • 52
  • 202
  • 249
-1

You could use the peventDefault() method

Moudinho
  • 309
  • 4
  • 6