I have a HTML text field where I'm adding unique values to my database. At the moment I'm using PHP to validate that the value entered in the text field does not already exist in my database. I wonder if this is possible to achieve with JavaScript so that I can prevent the form from submitting if there is an error.
EDIT: This is how I've come so far
The JavaScript is executed in the form-tag by onsubmit="return validateForm()". I get the "System Error!" message and the form is submitted even though I say it should not.
function validateForm(){
// Get all elements with the required-class
var x = document.getElementsByClassName('required');
var submitForm = true;
for(var i = 0; i < x.length; i++){
// Fetch input
var input = x[i];
// Fetch input value
var inputValue = input.value;
if(input.disabled == false){
// Check if the value exist
if(inputValue == null || inputValue == ''){
// Red border
input.style.borderColor = "#ff0000";
// Don't submit the form
submitForm = false;
} else if(input.name == 'company'){
$.ajax({
type: 'GET',
url: '../includes/ajax_mysql.php?company='+input.value,
success: function(data){
if(data == '1'){ submitForm = false; } else{ submitForm = true; }
alert(data);
},
error: function(data){
submitForm = false;
alert("System Error!");
}
});
}
}
}
if(!submitForm){ return false; } else{ return true; }
}