0

I have tried by using the below code but the error message disappears quickly

$(document).ready(function () {
    $('form').submit(function () {
        if ($("#first").val().match('^[a-zA-Z]{3,16}$')) {
            alert("valid");
        } else {
            $("#error_msg").after("invalid");
        }
    })
})
tamil
  • 83
  • 1
  • 7

4 Answers4

1

Use preventDefault() method to stop the default action of an element from happening:

$(document).ready(function(){
  $('form').submit(function(e){
    if($("#first").val().match('^[a-zA-Z]{3,16}$')){
       alert("valid");
    }
    else{
      e.preventDefault();
      $("#error_msg").after("invalid");
    }
  })
})
SilverSurfer
  • 4,281
  • 6
  • 24
  • 50
  • but if i try to click submit again error message(invalid) is showing continuously like invalidinvalidinvalid – tamil Sep 06 '17 at 10:29
1

Use event.preventDefault().If this method is called, the default action of the event will not be triggered.

$(document).ready(function() {
  $('form').submit(function(event) {
    if ($("#first").val().match('^[a-zA-Z]{3,16}$')) {
      alert("valid");
    } else {
       $("#error_msg").empty().text("invalid");
       alert("invalid");
      event.preventDefault();
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="first">
<div id="error_msg"></div>
<button type="submit">submit</button>
</form>
XYZ
  • 4,450
  • 2
  • 15
  • 31
0

Use return false;

$(document).ready(function(){
  $('form').submit(function(e){
    if($("#first").val().match('^[a-zA-Z]{3,16}$')){
       alert("valid");
    }
    else{      
      $("#error_msg").after("invalid");
       return false;
    }
  })
})
Athul Nath
  • 2,536
  • 1
  • 15
  • 27
0

Use return false or preventDefault() method to stop the action :

$(document).ready(function(){
  $('form').submit(function(e){
    if($("#first").val().match('^[a-zA-Z]{3,16}$')){
       alert("valid");
    }
    else{
      $("#error_msg").after("invalid");
      return false;
      //or
      e.preventDefault();
    }
  })
})
Govind Samrow
  • 9,981
  • 13
  • 53
  • 90