I made a simple form validation. It's working alright. The thing is I want my code to be optimized. Can somebody show me some pointers to improve my code? Thanks in advance.
$(document).ready(function(){
$('.submit').click(function(){
validateForm();
});
function validateForm(){
var nameReg = /^[A-Za-z]+$/;
var numberReg = /^[0-9]+$/;
var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
var names = $('#nameInput').val();
var company = $('#companyInput').val();
var email = $('#emailInput').val();
var telephone = $('#telInput').val();
var message = $('#messageInput').val();
var inputVal = new Array(names, company, email, telephone, message);
var inputMessage = ["name", "company", "email address", "telephone number", "message"];
var textId = ["#nameLabel", "#companyLabel", "#emailLabel", "#telephoneLabel", "#messageInput"];
$('.error').hide();
if($.trim(inputVal[0]) === ""){
$('#nameLabel').after('<span class="error"> Please enter your ' + inputMessage[0] + '</span>');
}else if(!nameReg.test(names)){
$('#nameLabel').after('<span class="error"> Letters only</span>');
}
if($.trim(inputVal[1]) === ""){
$('#companyLabel').after('<span class="error"> Please enter your ' + inputMessage[1] + '</span>');
}
if($.trim(inputVal[2]) === ""){
$('#emailLabel').after('<span class="error"> Please enter your ' + inputMessage[2] + '</span>');
}else if(!emailReg.test(email)){
$('#emailLabel').after('<span class="error"> Please enter a valid email address</span>');
}
if($.trim(inputVal[3]) === ""){
$('#telephoneLabel').after('<span class="error"> Please enter your ' + inputMessage[3] + '</span>');
}else if(!numberReg.test(telephone)){
$('#telephoneLabel').after('<span class="error"> Numbers only</span>');
}
if($.trim(inputVal[4]) === ""){
$('#messageLabel').after('<span class="error"> Please enter your ' + inputMessage[4] + '</span>');
}
return false;
}
});