Reputation: 871
So I'm trying to validate a form and I'm not being able to get the textbox change when the validation fails. Instead, the form gets completed. What I want is if the validation fails, the textbox border becomes color red and a text in red just below the textbox which says "Fill our this field!"
Here's what I have written just for the purpose of testing and it's not working and I'm not sure how to add the red=colored text just after the box concerned:
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
var formIsValid = true;
if(first.value === ""){
//Not sure how to add Red-Colored Text below the box which says "Fill our this field!"
first.borderColor = "red"; //NOT WORKING
formIsValid = false;
}
return formIsValid;
}
Upvotes: 2
Views: 7579
Reputation: 540
I think for text, you can use empty lable to make a text appear just below the textbox which say "Fill this textbox" on validation failure.
Upvotes: 0
Reputation: 1446
I believe this is what you are looking for,
<form name= "reg" id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<input type="submit">Register</button>
</form>
function validate(){
var formIsValid = true;
var first=document.forms["reg"]["first"];
if(first.value == null || first.value == ""){
first.style.borderColor = "red";
formIsValid = false;
}
return formIsValid;
}
Upvotes: 5