I created a form with an input field that captures the user's mobile number and validates it to ensure it begins with '0'. The validation process is functioning correctly, but I am encountering a problem when submitting the form. Even if the input field contains an invalid value, the form is still submitted. I would like the form to only be submitted if the field has a valid mobile number input.
Below is the code snippet:
$('#mobili').focusout(function() {
$('#mobili').filter(function() {
var mobi = $('#mobili').val();
var mobiback = $('#mobili');
var mobilReg = /^([0][0-9]{10})$/;
if (!mobilReg.test(mobi)) {
$("#error-nwl").css('color', '#ff6666');
$("#error-nwl").text("Enter a valid mobile number (must begin with 0)");
} else {
$("#error-nwl").css('color', '#66cc66');
$("#error-nwl").text("ok");
}
})
});
$(".newslside").submit(function(e) {
var url = "page2.html";
alert("Submitted");
$.ajax({
type: "POST",
url: url,
data: $(".newslside").serialize(),
success: function(data) {
$(".errori").html(data),
alert("Submitted");
}
});
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="error-nwl"></div>
<form action="" method="post" name="myForm" class="newslside">
<input type="text" placeholder="Mobile" name="mobile" id="mobili" maxlength="11" required />
<br/>
<button class="submitnews" type="submit">Send</button>
</form>
Thank you