JS validation highlight input field red / green

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.

+7
javascript html
source share
2 answers

You are missing } at the end, but also it works fine.

Here's a working fiddle: http://jsfiddle.net/aJ2Tw/

And updated code:

  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"; } } 
+5
source share

if ($ ('# TextBoxID'). val () == '') {$ ('# TextBoxID'). Css ('border-color', 'red'); } else {$ ('# TextBoxID'). Css ('border-color', ''); }

+3
source share

All Articles