简体   繁体   English

Javascript 中的表单验证和重定向

[英]Form validation and redirect in Javascript

I am writing a simple form program, but I have issues with the registration and log in.我正在编写一个简单的表单程序,但我在注册和登录时遇到问题。

This is how I want it to work:这就是我希望它的工作方式:

  • I create a simple registration form that requires just email and password我创建了一个简单的注册表单,只需要 email 和密码

  • I want the user to fill in, and if the username doesn't exists in my local storage, it gives a registration success in the inner html and redirects the user to the login page, where the login should get the value of the registered user我希望用户填写,如果用户名在我的本地存储中不存在,它会在内部 html 中注册成功并将用户重定向到登录页面,登录应该获取注册用户的值

  • If that value tallies with what the user input on registration, redirect to a welcome page with the user's ID he input on registration如果该值与用户在注册时输入的内容相符,则使用他在注册时输入的用户 ID 重定向到欢迎页面

  • Else give an error that says the username exists, and don't redirect the user to the login page at all.否则会给出一个错误,指出用户名存在,并且根本不将用户重定向到登录页面。

If you don't understand the above question, check this if it makes it clearer:如果您不理解上述问题,请检查此问题是否更清楚:

  • I am creating a registration form, so that if I register a user ID the first time, it gives me success and redirects to the log in. If i use that same ID again to register, it gives me an error stating that the ID has been registered.我正在创建一个注册表单,所以如果我第一次注册用户 ID,它会给我成功并重定向到登录。如果我再次使用相同的 ID 进行注册,它会给我一个错误,指出 ID 有已注册。

  • Now, after the user registers, he should be redirected to the login with a valid ID already submitted on registration现在,在用户注册后,他应该被重定向到登录时已经提交了一个有效的 ID

  • If the ID entered doesn't match any of the ID's on registration, don't direct the user to the welcome page, else redirect to the welcome page and say "Welcome User xyz" with the User ID registered with from the registration page.如果输入的 ID 与注册时的任何 ID 不匹配,请不要将用户定向到欢迎页面,否则重定向到欢迎页面并使用注册页面中注册的用户 ID 说“欢迎用户 xyz”。

Below is my code:下面是我的代码:

registeration code:注册码:

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

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/bootstrap.css">
        <title>Registration</title>
    </head>
    
    <body>
        <div class="container text-center mt-5">
            <h1>Welcome! Please register below</h1>
            <form action="" class="pt-3">
    
    
                <p class="text-danger message_error text-center"></p>
                <p class="text-success message_success text-center"></p>
    
    
                <div class="form-row">
                    <!-- username -->
                    <div class="col-md-12 mt-5">
                        <input maxlength="10" type="text" class="form-control p-3 username" placeholder="Enter Username"
                            required>
                    </div>
                    <!-- password -->
                    <div class="col-md-12 mt-5">
                        <input type="password" class="form-control p-3 password" class="password" placeholder="Enter password"
                            maxlength="8" required>
                    </div>
                    <!-- submit -->
                    <div class="col-md-6 p-3">
                        <input type="submit" value="Register" class="w-100 btn btn-primary" onclick="redirect();">
                    </div>
                   
                </div>
            </form>
            <a href="login.html"><div class="col-md-6 p-3">
            </div></a>
        </div>
        
        <script>
            const $form = document.querySelector("form");
    $form.addEventListener('submit', processRegistration);
    
    
    function processRegistration(event) {
        event.preventDefault();
        const $username = document.querySelector(".username").value;
        const $password = document.querySelector(".password").value;
        const $errorBox = document.querySelector(".message_error")
        const $successBox = document.querySelector(".message_success")
        $errorBox.innerHTML = "";
        $successBox.innerHTML = "";
    
    
    
        //  check if the browser supports this API
        if (localStorage != (null || undefined)) {
            // validate if username exists in our local storage
            const usernameExists = localStorage.getItem($username);
            if (usernameExists == null) {
                //    add user record to local storage
                localStorage.setItem($username, $password);
                $successBox.innerHTML = "Registration Successful";
                function redirect() {
        setTimeout(function(){
            window.location.href = "login.html";
        },5000
        );
    }
    
                
    
            } else {
                $errorBox.innerHTML = "Sorry! This Username already exists";
            }
        }
    
    }
    
    
    
    
    
        </script>
    </body>
    
</html>

log in code登录代码

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <link rel="stylesheet" href="css/bootstrap.css">
        <title>Login Page</title>
    </head>
    <body>
    
        <div class="container text-center mt-5">
            <h1>Kindly fill in your details below, to Login</h1>
            <form action="" class="pt-3">
    
    
                <p class="text-danger message_error text-center"></p>
                <p class="text-success message_success text-center"></p>
    
    
                <div class="form-row">
                    <!-- username -->
                    <div class="col-md-12 mt-5">
                        <input maxlength="10" type="text" class="form-control p-3 username" placeholder="Enter Username"
                            required>
                    </div>
                    <!-- password -->
                    <div class="col-md-12 mt-5">
                        <input type="password" class="form-control p-3 password" class="password" placeholder="Enter password"
                            maxlength="8" required>
                    </div>
                    <!-- submit -->
                    <div class="col-md-6 p-3">
                        <input type="submit" value="Login" class="w-100 btn btn-primary" onclick="redirect();">
                    </div>
                    
                </div>
            </form>
            <a href="welcome.html"><div class="col-md-6 p-3">
            </div></a>
        </div>
       <script>
           const $form = document.querySelector("form");
    $form.addEventListener('submit', processLogin);
    
    
    function processLogin(event) {
        event.preventDefault();
        const $username = document.querySelector(".username").value;
        const $password = document.querySelector(".password").value;
        const $errorBox = document.querySelector(".message_error")
        const $successBox = document.querySelector(".message_success")
        $errorBox.innerHTML = "";
        $successBox.innerHTML = "";
    
    
    
        //  check if the browser supports this API
        if (localStorage != (null || undefined)) {
            // validate if username exists in our local storage
            const usernameExists = localStorage.getItem($username);
            if (usernameExists == null) {
                //    add user record to local storage
                localStorage.getItem($username, $password);
                $successBox.innerHTML = "Login Successful";
    
                function redirect() {
        setTimeout(function(){
            window.location.href = "welcome.html";
        },1000
        );
    }
    
            } else {
                $errorBox.innerHTML = "Sorry! This Username doesn;t exists, create a profile";
            }
        } else {
            $errorBox.innerHTML = "please update your browser :";
        }
    
    }
    
    
    
    
       </script>
    </body>
</html> 

welcome page欢迎页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.css">
    <title>Welcome Page</title>
</head>
<body>
   <h1>Welcome to Our Site! We are glad you're here</h1>
   <script>

   </script>
</body>
</html>

Perhaps the following might be of use.也许以下内容可能有用。 Rather than using the submit event a regular click event on the submit button seems appropriate?而不是使用submit事件,提交按钮上的常规click事件似乎合适? Due to security surrounding access to localStorage here on Stack I could not create a working snippet but local copies of this and all seemed to work.由于在 Stack 上访问 localStorage 的安全性,我无法创建一个工作片段,但它的本地副本和所有似乎都可以工作。

Registration:登记:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/bootstrap.css">
        <title>Registration</title>
    </head>
    <body>
        <div class="container text-center mt-5">
            <h1>Welcome! Please register below</h1>
            
            <form method='post' name='register' class="pt-3">
                <p class="text-danger message_error text-center"></p>
                <p class="text-success message_success text-center"></p>
                <div class="form-row">
                    <div class="col-md-12 mt-5">
                        <input name='username' maxlength="10" type="text" class="form-control p-3 username" placeholder="Enter Username" required />
                    </div>
                    <div class="col-md-12 mt-5">
                        <input name='password' type="password" class="form-control p-3 password" class="password" placeholder="Enter password" maxlength="8" required />
                    </div>
                    <div class="col-md-6 p-3">
                        <input type="submit" value="Register" class="w-100 btn btn-primary" />
                    </div>
                </div>
            </form>
            <a href="login.html">
                <div class="col-md-6 p-3"></div>
            </a>
        </div>
        
        <script>
            /*
                Some shorthand utility methods to simplify
                calls to certain functions.
            */
            const q=(n,ex)=>n.querySelector(ex);
            const qa=(n,ex)=>n.querySelectorAll(ex);
            const msg=(n,s)=>q(form,n).textContent=s;
            
            /*
                Once the form has been assigned a Name attribute
                you can easily refer to the form using the dot
                notation shown here.
            */
            const form=document.forms.register;
            
            /*
                using the shorthand method above to obtain a 
                reference to the `submit` button to which we 
                assign the event handler - bound to the click
                event.
            */
            q( form, "input[type='submit']" ).addEventListener('click', function(e){
                e.preventDefault();
                /*
                    find form elements - again if names are
                    assigned you can use the dot notation.
                */
                const username=form.username.value;
                const password=form.password.value;
                const exists=localStorage.getItem( username )!==null;
                
                if( exists ){
                    // username already exists...
                    msg('p.message_error','Sorry! This Username already exists');
                }else{
                    // add username to storage
                    localStorage.setItem(username,password);
                    msg('p.message_success','Registration Successful');
                    
                    setTimeout( ()=> window.location.replace("login.html"), 5000 );
                }
            })
        </script>
    </body>
</html>

Login:登录:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/bootstrap.css">
        <title>Login page</title>
    </head>
    <body>
        <div class="container text-center mt-5">
            <h1>Kindly fill in your details below, to Login</h1>
            
            <form method='post' name='login' class="pt-3">
                <p class="text-danger message_error text-center"></p>
                <p class="text-success message_success text-center"></p>
                
                <div class="form-row">
                    <div class="col-md-12 mt-5">
                        <input name='username' maxlength="10" type="text" class="form-control p-3 username" placeholder="Enter Username" required />
                    </div>
                    <div class="col-md-12 mt-5">
                        <input name='password' type="password" class="form-control p-3 password" class="password" placeholder="Enter password" maxlength="8" required />
                    </div>
                    <div class="col-md-6 p-3">
                        <input type="submit" value="Register" class="w-100 btn btn-primary" />
                    </div>
                </div>
            </form>
            <a href="login.html">
                <div class="col-md-6 p-3"></div>
            </a>
        </div>
        
        <script>
            const q=(n,ex)=>n.querySelector(ex);
            const qa=(n,ex)=>n.querySelectorAll(ex);
            const msg=(n,s)=>q(form,n).textContent=s;
            const form=document.forms.login;

            q( form,"input[type='submit']" ).addEventListener('click', function(e){
                e.preventDefault();
                
                const username=form.username.value;
                const password=form.password.value;
                const exists=localStorage.getItem( username )!==null;
                
                if( !exists ){
                    // username does NOT exist...
                    msg('p.message_error','Sorry! This Username doesn\'t exists, please create a profile!');
                }else{
                    // Everything OK... proceed to welcome page
                    msg('p.message_success','Login Successful');
                    
                    // Set a cookie to log which user has successfully logged in. This will be read on `welcome.html`
                    document.cookie='username='+username;
                    
                    // redirect to the welcome page
                    setTimeout( ()=>window.location.replace("welcome.html"), 5000 );
                }
            })
        </script>
    </body>
</html>

Welcome:欢迎:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.css">
    <title>Welcome Page</title>
</head>
<body>
   <h1>Welcome to our site! We are glad you're here</h1>
   <span></span>
   <script>
        const q=(n,ex)=>n.querySelector(ex);
        const msg=(n,s)=>q(document,n).textContent=s;
        
        // read the cookie and extract the username.. no error checking here - this was for brevity
        let username=document.cookie.split(';').find( row=>row.startsWith('username') ).split('=')[1]
        
        // display some sort of message...
        msg('span',['Hi there ',username,' take a seat and make yourself comfortable'].join(''));
   </script>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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