Forum Moderators: open

Message Too Old, No Replies

text fields validation

javascript textfield

         

ksugam

11:27 pm on Feb 4, 2008 (gmt 0)

10+ Year Member



Hello,
I have 2 text fields on my webpage, year (maxlength=4) and month (maxlength=3).
I want to make sure tht the user inputs valid year and month. Can anyone please help me out with this?

I also need help with one more issue:
for the same text boxes, when i page loads on the browser, i want to display yyyy in the year box and mmm in the month box. when the user clicks on the box, the yyyy (or mmm) should disappear and user can type what he wants...

Would appreciate help with this...

eelixduppy

8:59 pm on Feb 5, 2008 (gmt 0)



For the "validation" part, you could do something like this:

if(document.getElementById("year").length > 4) {
alert("That year is too long!");
}
else if(document.getElementById("month").length > 3) {
alert("That month is too long!");
}

As far as making the input field blank when it is clicked on, you can do something like the following:


<input type="text" value="test" onClick="this.value='';" />

This will replace whatever is in there with nothing. This does, however, present a problem if information is typed into the input box and then clicked again as the info typed would be lost. To prevent this, you might want to write a function that checks to see if the content actually changes from what it originally is, and if it did then it won't replace it with a blank field. IE:


function clear(field) {
if(field.value == "test") {
field.value = '';
}
}

Hope this helps :)

eelixduppy

9:00 pm on Feb 5, 2008 (gmt 0)



Almost forgot. But as a note, you should also validate your forms server-side in addition to what you want to do here. This is for multiple reasons, but the biggest is that javascript validation can be avoided and you can get unexpected results server-side that may be potentially harmful to your application.