I have an HTML form which I am validating using JavaScript like below code. All the JavasCript code is in an app.js file.
App.js file
function validateForm () {
var amount = document.forms["salesform"]["amount"];
var buyer = document.forms["salesform"]["buyer"];
var buyerRegex = /^[a-zA-Z0-9_ ]*$/;
var receipt_id = document.forms["salesform"]["receipt_id"];
var receiptIdRegex = /^[a-zA-Z_ ]*$/;
let items = document.querySelectorAll(".items")
var itemsRegex = /^[a-zA-Z_ ]*$/;
var buyer_email = document.forms["salesform"]["buyer_email"];
var note = document.forms["salesform"]["note"];
var city = document.forms["salesform"]["city"];
var cityRegex = /^[a-zA-Z_ ]*$/;
var phone = document.forms["salesform"]["phone"];
var phoneRegex = /^[0-9]*$/;
var entry_by = document.forms["salesform"]["entry_by"];
var entryByRegex = /^[0-9]*$/;
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
if (amount.value == "") {
alert("Please enter the amount.");
amount.focus();
return false;
} else if (isNaN(amount.value)) {
alert("Amount must be only numeric value.");
amount.focus();
return false;
} else if (amount.length > 10 ) {
alert("Amount must be less than 10 characters long.");
amount.focus();
return false;
}
// more validation.....
return true;
}
In this file I have another jQuery Ajax code validate the form using Server. So that I have added following Ajax code blow that JS validation code:
$("#salesForm").submit(function(e) {
e.preventDefault();
$.ajax({
url : '../process/add-data.php',
type: 'POST',
dataType: "html",
data : $(this).serialize(),
beforeSend : function () {
$(".formResult").html("Please wait...");
},
success : function ( data ) {
$(".formResult").html( data );
}
});
});
for the HTML form
<form name="salesform" id="salesForm" onsubmit="return validateForm();" method="POST">
Now when the form is validating using JavaScript then it also vaidating the form using Ajax.
But first its should validate using JavaScript and then Ajax.