Reputation: 113
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");
}
})
})
Upvotes: 0
Views: 1557
Reputation: 4480
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>
Upvotes: 1
Reputation: 10179
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();
}
})
})
Upvotes: 0
Reputation: 2606
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;
}
})
})
Upvotes: 0
Reputation: 4366
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");
}
})
})
Upvotes: 1