Jump to content

Form validation


POWERPLAY27

Recommended Posts

Ok I have my form The fields I have are fullName, contactNo, email. If no value is inserted I want the writing i.e. Full Name:, Contact No:, Email address: to change color to red and have a star beside them: e.g. Full Name:* I have a css document, so I would like Javascript to access that and change the color of the particular fieldname which I have......fullName{}, if there is no value inserted in the field or if there is a wrong data type in the field.....i.e. a letter instead of numbers in the Contact No field. Any ideas how I will be able to do this and is javascript the best language for this task?

Link to comment
Share on other sites

Yes, JavaScript is the language you want to use. The concept is simple. Assign an event handler to each of your inputs on the onblur or onchange events. The handler accepts one parameter, the element to be validated. Since you want to change the label on the input, you'll need to make sure your HTML is set up to easily select the label in relation to the input. An example of how you might set up the HTML:

<label for='full_name'>Full Name:</label><input type='text' id='full_name' value='' />

This will allow you to use the previousSibling property to access the label. As for the event handler, I'll set it up for you to show the technique, but I'll leave the guts of it up to you to figure out.

function validate(el) {   //This part you'll need to try to figure out on your own first}

And call it like this in your input elements:

<input type='text' id='id_here' value='' onchange='validate(this);' />

The this keyword passes a reference to the element firing the event to the event handler. Within the event handler, you'll need to use the el variable (this is the reference to the element) to check the element's value and, if invalid, change the color of the label. Here are some references:EventsThe value propertyThe style propertypreviousSibling

Link to comment
Share on other sites

I can give you a piece of code that does that right away, as I've applied that to my form but in a different way; I have made it turn the box area RED when it is found to be Empty.If you'd like that I can help you as much as I can.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...