I am creating a simple JS validation for my HTML form. The validation checks if the fields are empty and in some cases checks both, if they're empty and input !numbers. This check works well but what I am also trying to achieve is to highlight the field in red if JS detects invalid input. I have coded some JS to style the input field if the input is invalid but it is the highlight that does not work.
JS snap
function FormValidation(){
//First Name Validation
var fn=document.getElementById('firstname').value;
if(fn == ""){
alert('Please Enter First Name');
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
if (/^[0-9]+$/.test(document.getElementById("firstname").value)) {
alert("First Name Contains Numbers!");
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
if(fn.length <=2){
alert('Your Name is To Short');
document.getElementById('firstname').style.borderColor = "red";
return false;
}else{
document.getElementById('firstname').style.borderColor = "green";
}
HTML snap
<form action="" method="post" onsubmit="return FormValidation();" onchange="return FormValidation();">
<div class="input-wrapper">
<input type="text" placeholder="First Name" id="firstname" name="name"/>
</div>
</form>
I'm quite sure the highlight should work. I've done similar validation before but unfortunately, this time can't get the result I'm after.
var firstName = document.getElementById('firstname')
you'll make your code easier to read and better performing.