简体   繁体   English

表单验证 JavaScript 后打开一个新页面

[英]Open A New Page After Form Validation JavaScript

I want to open a new page after i validated my form.There is no problem with validating it .But my form never submits ,and the html page i want to redirect to my form is not opening ,it stuck in the same page after validation.Im trying to do this in addEventListener .After user clicked the submit button it should open the page i want ,but i could not solve the problem My html code...我想在验证我的表单后打开一个新页面。验证它没有问题。但是我的表单从不提交,我想重定向到我的表单的 html 页面没有打开,它在验证后卡在同一个页面.我试图在 addEventListener 中执行此操作。用户单击提交按钮后,它应该打开我想要的页面,但我无法解决问题我的 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">
    <title>Form Validation</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./style.css">
    <script defer src="./index.js"></script>
</head>
<body>
    <div class="container">
        <form id="form" action="/">
            <h1>Registration</h1>
            <div class="input-control">
                <label for="username">Username</label>
                <input id="username" name="username" type="text">
                <div class="error"></div>
            </div>
            <div class="input-control">
                <label for="email">Email</label>
                <input id="email" name="email" type="text">
                <div class="error"></div>
            </div>
            <div class="input-control">
                <label for="myArea">Subject</label>
                <textarea  name="myArea" id="myArea"rows="10" cols="45"  placeholder="Please enter your thoughts on this.."></textarea>
                <div class="error"></div>
            </div>

            <button type="submit" id="buton" name="buton" >Sign Up</button>
        </form>
    </div>
</body>
</html>

My javascript code..我的javascript代码..

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const myArea = document.getElementById('myArea');
var isValid1=false;
var isValid2=false;
var isValid3=false;

form.addEventListener('submit', e => {
    e.preventDefault();

    validateInputs();
    if(isValid1 && isValid2 && isValid3){
        this.submit();
        window.location("action.html");
      }
});


const setError = (element, message) => {
    const inputControl = element.parentElement;
    const errorDisplay = inputControl.querySelector('.error');

    errorDisplay.innerText = message;
    inputControl.classList.add('error');
    inputControl.classList.remove('success')
}

const setSuccess = element => {
    const inputControl = element.parentElement;
    const errorDisplay = inputControl.querySelector('.error');

    errorDisplay.innerText = '';
    inputControl.classList.add('success');
    inputControl.classList.remove('error');
};

const isValidEmail = email => {
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

const validateInputs = () => {
    const usernameValue = username.value.trim();
    const emailValue = email.value.trim();
    const myAreaValue = myArea.value;
    
    if(usernameValue === '') {
        isValid1=false;
        setError(username, 'Name is required');
        
    } else {
        isValid1=true;
        setSuccess(username);
        
    }

    if(emailValue === '') {
        isValid2=false;
        setError(email, 'Email is required');
        
    } else if (!isValidEmail(emailValue)) {
        isValid2=false;
        setError(email, 'Please enter a valid email');
        
    } else {
        isValid2=true;
        setSuccess(email);
    }

    if(myAreaValue === '') {
        isValid3=false;
        setError(myArea, 'Subject is required');
        
    }else {
        isValid3=true;
        setSuccess(myArea);
    }
};

Replace your eventListener to this:将您的 eventListener 替换为:

form.addEventListener('submit', e => {
    e.preventDefault();

    validateInputs();
    if(isValid1 && isValid2 && isValid3){
        form.submit();
        window.location("action.html");
      }
});

The submit() function has to be called by the form. submit()函数必须由表单调用。

Check the documentation here: https://www.w3schools.com/jsref/met_form_submit.asp在此处查看文档: https ://www.w3schools.com/jsref/met_form_submit.asp

You should also take care on window.location("action.html") since window.location is not a function, try instead window.location.href = "action.html";您还应该注意window.location("action.html")因为window.location不是函数,请尝试改为window.location.href = "action.html"; . . See this answer for more examples.有关更多示例,请参见此答案

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

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