开发者

Only submit form if a condition is met?

Right now I have a basic shopping cart setup. When a user enters their information, I want to write this data to a XML file. To do this I have been using the POST method of submitting the form. However, I only want to submit this form to be saved if it meets conditions (like using a regular expression to make sure no letters are in the phone number).

So my form is like this:

<form action= "confirmation.php" name="memberData" method="post">
        <input name="textField" id="textField"></input>
        <input type="submit" name="submitbutton" id="submitbutton" onclick="submitIt()" value="Submit Button"/>
    </form>

So what I want is to call this submitIt() function that checks if the data is valid. If it is valid then I want to perform my form action. Otherwise, I want it to not redirect until the user fixes thei开发者_开发技巧r entered information. Right now it does properly alert the user of a incorrect field but immediately after it redirects and saves the information anyways.

Is there a way to only perform a form action if it meets certain conditions?


What you want to do here is prevent the default action of the event, in your case form submission. To do that the handler should return false. In order for that to work you have to change the handler from onClick of the submit button to onSubmit of the form.

You can also read up a little about events here http://www.quirksmode.org/js/introevents.html.


You could do something like this:

<form ... onsubmit="return submitIt();">

Where submitIt() is a javascript function that returns true if valid, false if invalid.


You need to stop the processing of the form by canceling the event that is being processed. See this example.

Note that this will obviously not run if JavaScript is disabled, so you still need to perform these checks server-side and handle the validation error appropriately server-side.


Also, check out the many JQuery plugins for this.

http://plugins.jquery.com/plugin-tags/form-validation

After getting past a few simple examples and getting everything included properly in the page, form validation becomes very easy and flexible across all of your sites.

Also, I really see the need for client-side validation without the user leaving the page,but don't forget that you MUST still sanitize and check form fields when the form is submitted. A malicious user can simply disable JavaScript to get past validation or a user running around with NoScript won't even realize there is validation taking place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜