I am creating a simple JS validation for my HTML form. The check checks if the fields are empty and in some cases checks them if they are empty and the numbers entered. This check works well, but what I'm also trying to achieve is to highlight the field in red if JS detects invalid input. I encoded some JS to create an input field if the input is not valid, but it is a 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 am absolutely sure that this should work. I already did a similar check before, but, unfortunately, this time I canβt get the result that I get after.
javascript html
Tomazi
source share