dongqingcheng2903 2017-06-09 20:59
浏览 123

Javascript FirstName LastName验证错误

I have copied this .js code from wikihow & github for validating user input on the registration form. Original form didn't have first name & last name. So I modified it. But now it's only working for 1st user input empty values. But for the rest, it keep showing

'Passwords must contain at least one number, one lowercase, and one uppercase letter. Please try again'

even after inputting right type of password. For other wrong input, it keeps showing

'Your password and confirmation do not match. Please try again'

I tried adding if else condition but that shows errors in netbean IDE. Hers is the javacode:

function formhash(form, password) {
    // Create a new element input, this will be our hashed password field. 
    var p = document.createElement("input");

    // Add the new element to our form. 
    form.appendChild(p);
    p.name = "p";
    p.type = "hidden";
    p.value = hex_sha512(password.value);

    // Make sure the plaintext password doesn't get sent. 
    password.value = "";

    // Finally submit the form. 
    form.submit();
}

function regformhash(form, uid, email, firstname, lastname, password, conf) {
    // Check each field has a value
    if (uid.value === '' || email.value === '' || firstname.value === '' || lastname.value === '' || password.value === '' || conf.value === '') {
        alert('You must provide all the requested details. Please try again');
        return false;
    }
    
    // Check the username
    var re = /^\w+$/; 
  if (!re.test(form.username.value)) { 
        alert("Username must contain only letters, numbers and underscores. Please try again"); 
        form.username.focus();
        return false; 
    }
    // Check the first name only letters
    var res = /^[a-zA-Z]+$/; 
 if(!res.test(form.firstname.value)) { 
        alert("firstname must contain only letters. Please try again"); 
        form.firstname.focus();
        return false; 
    }
    // Check the last name only letters
    var ree = /^[a-zA-Z]+$/; 
  if(!ree.test(form.lastname.value)) { 
        alert("lastname must contain only letters. Please try again"); 
        form.lastname.focus();
        return false; 
    }
    // Check that the password is sufficiently long (min 6 chars)
    // The check is duplicated below, but this is included to give more
    // specific guidance to the user
    if (password.value.length < 6) {
        alert('Passwords must be at least 6 characters long.  Please try again');
        form.password.focus();
        return false;
    }
    
    // At least one number, one lowercase and one uppercase letter 
    // At least six characters 
    var rek = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/; 
    if (!rek.test(password.value)) {
        alert('Passwords must contain at least one number, one lowercase and one uppercase letter.  Please try again');
        form.password.focus();
        return false;
    }
    
    // Check password and confirmation are the same
    if (password.value !== conf.value) {
        alert('Your password and confirmation do not match. Please try again');
        form.password.focus();
        return false;
    }
        
    // Create a new element input, this will be our hashed password field. 
    var p = document.createElement("input");

    // Add the new element to our form. 
    form.appendChild(p);
    p.name = "p";
    p.type = "hidden";
    p.value = hex_sha512(password.value);

    // Make sure the plaintext password doesn't get sent. 
    password.value = "";
    conf.value = "";

    // Finally submit the form. 
    form.submit();
    return true;
}

HTML + PHP Part:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Secure Login: Registration Form</title>
        <script type="text/JavaScript" src="js/sha512.js"></script> 
        <script type="text/JavaScript" src="js/forms.js"></script>
        <link rel="stylesheet" href="styles/main.css" />
    </head>
    <body>
        <!-- Registration form to be output if the POST variables are not
        set or if the registration script caused an error. -->
        <h1>Register with us</h1>
        <?php
        if (!empty($error_msg)) {
            echo $error_msg;
        }
        ?>
        <ul>
            <li>Usernames may contain only digits, upper and lower case letters and underscores</li>
            <li>Emails must have a valid email format</li>
            <li>Passwords must be at least 6 characters long</li>
            <li>Passwords must contain
                <ul>
                    <li>At least one upper case letter (A..Z)</li>
                    <li>At least one lower case letter (a..z)</li>
                    <li>At least one number (0..9)</li>
                </ul>
            </li>
            <li>Your password and confirmation must match exactly</li>
        </ul>
        <form method="post" name="registration_form" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
            Username: <input type='text' name='username' id='username' /><br>
            Email: <input type="text" name="email" id="email" /><br>
            First Name: <input type="text" name="firstname" id="firstname" /><br>
            Last Name: <input type="text" name="lastname" id="lastname" /><br>
            Password: <input type="password"
                             name="password" 
                             id="password"/><br>
            Confirm password: <input type="password" 
                                     name="confirmpwd" 
                                     id="confirmpwd" /><br>
            <input type="button" 
                   value="Register" 
                   onclick="return regformhash(this.form,
                                   this.form.username,
                                   this.form.email,
                                   this.form.firstname,
                                   this.form.lastname,
                                   this.form.password,
                                   this.form.confirmpwd);" /> 
        </form>
        <p>Return to the <a href="index.php">login page</a>.</p>
    </body>
</html>

Second PHP File:

<?php
include_once '*****.php';
include_once '*****.php';
 
$error_msg = "";
 
if (isset($_POST['username'], $_POST['email'],$_POST['firstname'],$_POST['lastname'], $_POST['p'])) {
    // Sanitize and validate the data passed in
    $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
    $firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
    $lastname = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING);
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        // Not a valid email
        $error_msg .= '<p class="error">The email address you entered is not valid</p>';
    }
 
    $password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
    if (strlen($password) != 128) {
        // The hashed pwd should be 128 characters long.
        // If it's not, something really odd has happened
        $error_msg .= '<p class="error">Invalid password configuration.</p>';
    }
    // Checking first name & lastname string count
    if (strlen($firstname) > 30) {
        // If it's not, something really odd has happened
        $error_msg .= '<p class="error">First Name should be within 30 Letters</p>';
    }
     if (strlen($lastname) > 30) {
        // If it's not, something really odd has happened
        $error_msg .= '<p class="error">Last Name should be within 30 Letters</p>';
    }
 
    // Username validity and password validity have been checked client side.
    // This should should be adequate as nobody gains any advantage from
    // breaking these rules.
    //
 
    $prep_stmt = "SELECT user_id FROM **** WHERE email = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);
 
   // check existing email  
    if ($stmt) {
        $stmt->bind_param('s', $email);
        $stmt->execute();
        $stmt->store_result();
 
        if ($stmt->num_rows == 1) {
            // A user with this email address already exists
            $error_msg .= '<p class="error">A user with this email address already exists.</p>';
                        $stmt->close();
        }
    } else {
        $error_msg .= '<p class="error">Database error Line 39</p>';
                $stmt->close();
    }
 
    // check existing username
    $prep_stmt = "SELECT user_id FROM **** WHERE username = ? LIMIT 1";
    $stmt = $mysqli->prepare($prep_stmt);
 
    if ($stmt) {
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $stmt->store_result();
 
                if ($stmt->num_rows == 1) {
                        // A user with this username already exists
                        $error_msg .= '<p class="error">A user with this username already exists</p>';
                        $stmt->close();
                }
        } else {
                $error_msg .= '<p class="error">Database error line 55</p>';
                $stmt->close();
        }
 
    // TODO: 
    // We'll also have to account for the situation where the user doesn't have
    // rights to do registration, by checking what type of user is attempting to
    // perform the operation.
 
    if (empty($error_msg)) {
 
        // Create hashed password using the password_hash function.
        // This function salts it with a random salt and can be verified with
        // the password_verify function.
        $password = password_hash($password, PASSWORD_BCRYPT);
 
        // Insert the new user into the database 
        if ($insert_stmt = $mysqli->prepare("INSERT INTO *** (username, email, firstname, lastname, password) VALUES (?, ?, ?, ?, ?)")) {
            $insert_stmt->bind_param('sssss', $username, $email, $firstname, $lastname, $password);
            // Execute the prepared query.
            if (! $insert_stmt->execute()) {
                header('Location: ../error.php?err=Registration failure: INSERT');
            }
        }
        header('Location: ./register_success.php');
    }
}
?>

UPDATE: On Jsfiddle its works fine. But not with my localhost: Here are screenshots: here password was okay Rubik123 but firstname lastname was not okay. But it is showing wrong error type. enter image description here Even for adding right data it still shows error.

SOLUTION: Solve the problem myself. As it was working correctly on JSfiddle, so feel coding can't be the problem (also as other members suggested). So I clear my broweser cache & then run it. Now JS file is working correctly so as the form. I didn't know browser cache cookies has a direct relation with this.

</div>

展开全部

  • 写回答

1条回答 默认 最新

  • dsnnvpobaljihv3490 2017-06-09 21:18
    关注

    This is working for me. Abc123456.

    function formhash(form, password) {
        // Create a new element input, this will be our hashed password field. 
        var p = document.createElement("input");
    
        // Add the new element to our form. 
        form.appendChild(p);
        p.name = "p";
        p.type = "hidden";
        p.value = hex_sha512(password.value);
    
        // Make sure the plaintext password doesn't get sent. 
        password.value = "";
    
        // Finally submit the form. 
        form.submit();
    }
    
    function regformhash(form, uid, email, firstname, lastname, password, conf) {
        // Check each field has a value
        if (uid.value === '' || email.value === '' || firstname.value === '' || lastname.value === '' || password.value === '' || conf.value === '') {
            alert('You must provide all the requested details. Please try again');
            return false;
        }
        
        // Check the username
        var re = /^\w+$/; 
      if (!re.test(form.username.value)) { 
            alert("Username must contain only letters, numbers and underscores. Please try again"); 
            form.username.focus();
            return false; 
        }
        // Check the first name only letters
        var res = /^[a-zA-Z]+$/; 
     if(!res.test(form.firstname.value)) { 
            alert("firstname must contain only letters. Please try again"); 
            form.firstname.focus();
            return false; 
        }
        // Check the last name only letters
        var ree = /^[a-zA-Z]+$/; 
      if(!ree.test(form.lastname.value)) { 
            alert("lastname must contain only letters. Please try again"); 
            form.lastname.focus();
            return false; 
        }
        // Check that the password is sufficiently long (min 6 chars)
        // The check is duplicated below, but this is included to give more
        // specific guidance to the user
        if (password.value.length < 6) {
            alert('Passwords must be at least 6 characters long.  Please try again');
            form.password.focus();
            return false;
        }
        
        // At least one number, one lowercase and one uppercase letter 
        // At least six characters 
        var rek = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/; 
        if (!rek.test(password.value)) {
            alert('Passwords must contain at least one number, one lowercase and one uppercase letter.  Please try again');
            form.password.focus();
            return false;
        }
        
        // Check password and confirmation are the same
        if (password.value !== conf.value) {
            alert('Your password and confirmation do not match. Please try again');
            form.password.focus();
            return false;
        }
            
        // Create a new element input, this will be our hashed password field. 
        var p = document.createElement("input");
    
        // Add the new element to our form. 
        form.appendChild(p);
        p.name = "p";
        p.type = "hidden";
        p.value = password.value;
    
        // Make sure the plaintext password doesn't get sent. 
        password.value = "";
        conf.value = "";
    
        // Finally submit the form. 
        form.submit();
        return true;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>Secure Login: Registration Form</title>
            <script type="text/JavaScript" src="js/sha512.js"></script> 
            <script type="text/JavaScript" src="js/forms.js"></script>
            <link rel="stylesheet" href="styles/main.css" />
        </head>
        <body>
            <!-- Registration form to be output if the POST variables are not
            set or if the registration script caused an error. -->
            <h1>Register with us</h1>
            <?php
            if (!empty($error_msg)) {
                echo $error_msg;
            }
            ?>
            <ul>
                <li>Usernames may contain only digits, upper and lower case letters and underscores</li>
                <li>Emails must have a valid email format</li>
                <li>Passwords must be at least 6 characters long</li>
                <li>Passwords must contain
                    <ul>
                        <li>At least one upper case letter (A..Z)</li>
                        <li>At least one lower case letter (a..z)</li>
                        <li>At least one number (0..9)</li>
                    </ul>
                </li>
                <li>Your password and confirmation must match exactly</li>
            </ul>
            <form method="post" name="registration_form" action="<?php echo esc_url($_SERVER['PHP_SELF']); ?>">
                Username: <input type='text' name='username' id='username' /><br>
                Email: <input type="text" name="email" id="email" /><br>
                First Name: <input type="text" name="firstname" id="firstname" /><br>
                Last Name: <input type="text" name="lastname" id="lastname" /><br>
                Password: <input type="password"
                                 name="password" 
                                 id="password"/><br>
                Confirm password: <input type="password" 
                                         name="confirmpwd" 
                                         id="confirmpwd" /><br>
                <input type="button" 
                       value="Register" 
                       onclick="return regformhash(this.form,
                                       this.form.username,
                                       this.form.email,
                                       this.form.firstname,
                                       this.form.lastname,
                                       this.form.password,
                                       this.form.confirmpwd);" /> 
            </form>
            <p>Return to the <a href="index.php">login page</a>.</p>
        </body>
    </html>

    </div>
    
    评论
编辑
预览

报告相同问题?