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 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..

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);
    }
};

>Solution :

Replace your eventListener to this:

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.

Check the documentation here: https://www.w3schools.com/jsref/met_form_submit.asp

Leave a Reply