Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Validating a form

Status
Not open for further replies.

tleish

Programmer
Jan 17, 2001
619
US
I'm trying to validate a form, and if it is valid then go to another URL using location.href. My problem is that sometimes it submits the page instead of using location.href, which I don't want it to do.

I'm calling it in the form tag using:
ONSUBMIT="checkLogin(this); return document.returnValue;"

Here's the script:
<SCRIPT LANGUAGE=&quot;JavaScript&quot;>
<!--//

// Form field values to check against
var vUserName = &quot;Joe Shmoe&quot;;
var vPass = &quot;&quot;;

// Where to next?
var vNext = &quot;
// Set default Error variable
var vErrors = &quot;&quot;;
// Check form
function checkLogin(vForm){
// If the username is correct, go to the next page
if(vForm.fUserName.value == vUserName){
location.href = vNext;
vErrors = &quot;&quot;;
}else{
// Set the error to wrong
vErrors = &quot;wrong&quot;;
}
// set the return variable
document.returnValue = (vErrors == '');
}

//-->
</SCRIPT>
 
i might be wrong but at a quick look i would say:

the code segment for ( // If the username is correct )
sets the location and then sets vErrors = ''
which would result in the function returning a true value to the onsubmit event
( that's assuming that the execution of the function code doesn't end when you set location.href = vNext; - i don't know how that works )

try changing it to
ONSUBMIT=&quot;checkLogin(this); return false;&quot;

hope that helps
 
Personally, I find it easier to validate each field during its onBlur method. If the fields aren't interdependent, this is easy.

However, if they are (field1=1, field2 can be a,b,c,or d; field1=2, field2 can be e,f,g,h), and you start with field1=1, field2=c, and change field1 to 2, you'll probably want to put the focus on field2 so they can chose e,f,g, or h.

Rose/Miros
 
So, you do want to submit the form though right? To avoid problems like this you could use an ordinary button -use onClick to do all your validation etc, then if you want to submit, just call document.formName.submit(), at any stage.

Just fiddle around with the order you give instructions, because sometimes submit does override things. BB &quot;Alright whatever man, I'll hook up the hair, but I aint touchin the ring...Cause I'm still a pla--yer&quot;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top