简体   繁体   中英

Getting JavaScript validation to work with PHP

<?php
if (isset($_POST['submit']) ) {
//send to database
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <script>
    function validateForm() {
        var usernameentry = document.forms["registrationform"]["username2"].value;
        var passwordentry = document.forms["registrationform"]["password2"].value;
        var nameentry = document.forms["registrationform"]["password2"].value;

        var emailentry = document.forms["registrationform"]["email"].value;
        var atpos = emailentry.indexOf("@");
        var dotpos = emailentry.lastIndexOf(".");



        if (usernameentry.length < 3  ||  username.length > 20){
            alert("Username must be inbetween 4 and 20 characters");
            return false;
        }

        else if (passwordentry.length < 3  ||  password.length > 20){
            alert("Password must be inbetween 4 and 20 characters");
            return false;
        }

        else if (nameentry.length < 3  ||  name.length > 45){
            alert("Name must be inbetween 4 and 45 characters");
            return false;
        }


        else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=emailentry.length  || emailentry.length > 154) {
            alert("Not a valid e-mail address");
            return false;
        }

        else
        {
            return true;
        }
    }
    </script>
</head>

<body>  
    <form name="registrationform" method="post" action="login.php" onsubmit="return validateForm();">

    Name: <input type="text" name="name"/>
    <br/>
    <br/>
    Email: <input type="text" name="email"/>
    <br/>
    <br/>
    Username: <input type="text" name="username2"/>
    <br/>
    <br/>
    Password: <input type="password" name="password2"/>
    <br/>
    <br/>
    <input type = "submit" name = "submit" value = "submit" />
    <br/>
    <br/>
    </form>
</body>

I want the contents of the if statement to run ONLY when the form has been validated with JavaScript, it runs regardless of whether the value returns is true or false.

I'm guessing what I need to do is similar to

if (isset($_POST['submit']) && onsubmit == true)

Obviously that's not right, but I don't know how to do it.

I know validating with php is a much more logical approach, but I need to demonstrate use of JavaScript.

You don't need to do that. When the form is validated, it will be sent to login.php

You can see this question HTML/Javascript: Simple form validation on submit

Also, there are a lot of libraries which could help you http://www.javascript-coder.com/html-form/javascript-form-validation.phtml

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