I\'m trying to validate a form using JavaScript but i\'m a bit stuck on displaying a message next to the field to say that \"This field is required\". How do I go about doing th
Your way of validation form fields is absolutely terrible, a lot of unneded and bloated code which is not optimized at all.
I will strongly reccomend you use some sort of readyly available FormValidation script or have a look at this jQuery plugin
Using jQuery your code can look like this (plus you also get the messages to appear next to field):
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
}
}
})
I think you need to take a look at this http://www.w3schools.com/js/js_form_validation.asp for the validation thing then take the ideas you have here to display your message.
Add a span near each field so you can use it for the validation message:
<td>First Name</td>
<td>
<input id="firstname" type="text" name="firstName" maxlength="30" />
<span id="firstname_error"/>
</td>
After that, just add the error message there, so instead of:
alert('You need to complete this field')
You would use:
document.getElementById('firstname_error').innerHTML = 'You need to complete this field'
I looked at the jQuery code. Looks like thousands of lines of code for some relatively simple validation. I would not recommend using the plugin for some simple validation - it is overkill.
Simplest way is to put a hidden span tag below the input field like so
<input .... /> <br />
<span id="fieldname" style="display: none;">This field is required</span>
In Javascript you can do this
if(!valid)
{
document.getElementById("fieldname").style = "block";
}