Forum Moderators: open

Message Too Old, No Replies

Adding min # characters to existing form code

Trying to edit existing code rather than rewritng it all

         

brizad

11:49 pm on Feb 22, 2007 (gmt 0)

10+ Year Member Top Contributors Of The Month



I don't write js but I'm comfortable editing it. I've got a couple issues with my current js validating a form, and I'm trying to just do a quick edit myself rather than taking the time and money to have the entire code rewritten.

I've got a 30 field form which has js validate there are no blank fields and also makes some fields visible/invisible based on certain selections.

The code that checks for blank fields is this:

if (Apply.firstn1.value == "") {
alert("Please enter your first name.");
Apply.firstn1.focus();
return false;
}

This is repeated about 30 times for the various fields. I'd like to set a minimum number of characters for certain fields so a person can't just enter a single letter for their name or 1 digit for their zip code.

I've tried about 6 different js examples that I've found online to modify the existing code but none of them have worked.

Is there a simple solution or few lines of code that I could add to my existing js to require a minimum number of characters?

Part 2

The code for the email is the same as above and just makes sure that it's not blank. I tried a couple of things I found online to validate if an email has the proper syntax, but couldn't get any of them to work either.

If there are any simple ways to add these functions I'd be glad to hear them. Thanks.

StupidScript

12:37 am on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Look at
string.length
[javascriptkit.com]

Fotiman

2:26 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Without seeing your entire validation code, I'm just going to provide a simple approach that's similar to what you already have. I personally would do it a little differently.

If this is your current code:

if (Apply.firstn1.value == "") {
alert("Please enter your first name.");
Apply.firstn1.focus();
return false;
}

You could modify that to something like this:

var minLen = 3;
if (Apply.firstn1.value.length < minLen) {
alert("Please enter your first name.");
Apply.firstn1.focus();
return false;
}

The example above requires the length to be at least 3 characters. However, it doesn't prevent the user from entering the spaces (but if they're going to enter 3 spaces, they could just as easily enter 3 other invalid values like "zzz" or "xyz", etc.).

brizad

10:52 pm on Feb 23, 2007 (gmt 0)

10+ Year Member Top Contributors Of The Month




var minLen = 3;
if (Apply.firstn1.value.length < minLen) {
alert("Please enter your first name.");
Apply.firstn1.focus();
return false;
}

That worked perfectly. Thanks very much!