Please Delete me
Please Delete me

Reputation: 871

Changing color of textbox and adding text on Javascript validation

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

Answers (2)

ranjeet
ranjeet

Reputation: 540

Have a look on this post

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

v2b
v2b

Reputation: 1446

I believe this is what you are looking for,

http://jsfiddle.net/F8H7Y/

<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

Related Questions