PDA

View Full Version : Validating Forms & submitting form data


carisue1027
11-12-2002, 05:10 AM
hello. I am very new to JavaScript. I have set up a web page with a form. The form is set to submit its data to: user_create.php.

<form method="get" action="user_create.php" name="user_form" onSubmit="validate_form()">

I have also declared a JavaScript function called validate_form - right now, the function is just checking the User Name to make sure its not blank.

The problem I'm having is that the function works OK - and if the User Name is blank - I get a little message saying the User Name is blank. BUT then the form submits to user_create.php. If the User Name is blank - I DO NOT want the form to be submitted. How do I tell my form this in my JavaScript? Here is what my JavaScript looks like now (the function validate_form()):

<script>
function validate_form ( )
{
var valid = true;
if (document.user_form.user_name.value == "" )
{
alert ( "Your User Name Is Missing." );
valid = false;
}
return valid;
}
</script>

I'm thinking I should add an if (validate_form()) - but after that I don't know how to tell JavaScript to submit the form. From what I've read, the submit() method allows you to submit a form w/o the user clicking the submit button. Is submit() appropriate in this situation as well?

if (validate_form())
{

}

beetle
11-12-2002, 05:18 AM
you need to cancel the submission event on the form itself.

<form onsubmit="return validate_form()">

I gave a detailed description of how this works here (http://www.codingforums.com/showthread.php?s=&threadid=8999).

Also, if you're interested, I've written a pretty extensive form validation tool that you can use. Click the fValidate link in my signature.

Cheers :D

carisue1027
11-12-2002, 05:32 AM
Thank you! This is just what I needed :-)

http://www.csndesign.com/images/horse6_50.jpg