简体   繁体   中英

Validate a PHP form using javascript

I am writing a PHP script to practice PHP form validation with Javascript. What I am expecting is the form to be validate by the function validate() specified in the onsubmit attribute, but instead I am redirected to the page adduser.php specified in the action attribute

I don't see what I've missed. Any help will be very welcomed.

 function validate(form) { alert("Inside validate form") return false }
 .signup { border: 1px solid #999; font: normal 14px Helvetica; color: #444; }
 <table class="signup" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee"> <th colspan="2" align="center">Signup Form</th> <form action="adduser.php" method="post" onsubmit="return validate(this);"> <tr> <td>Forename</td> <td><input type="text" name="forename" id="forename" maxlength="32"></td> </tr> <tr> <td>Surname</td> <td><input type="text" name="surname" id="surname" maxlength="32"></td> </tr> <tr> <td>Username</td> <td><input type="text" name="username" id="username" maxlength="16"></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" id="password" maxlength="12"></td> </tr> <tr> <td>Age</td> <td><input type="text" name="age" id="age" maxlength="3"></td> </tr> <tr> <td>Email</td> <td><input type="text" name="email" id="email" maxlength="64"></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="Signup"> </td> </tr> </form> </table>

A few things:

You are probably missing a this.preventDefault() , because the default action is to actually submit the form.

What you want to accomplish is called 'client-side validation', and while useful, should not replace server side (PHP) validation, because you can never trust the input from a client.

This behavior is expected. When the submit button is clicked the validate function is executed, followed by the default behavior of redirecting to the specified action .

In order to perform client-side validation, you need to prevent this default behavior by adding form.preventDefault() . After that, perform the validation and do the redirect yourself by adding window.location.href = "adduser.php" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM