简体   繁体   中英

How to submit form only when data in all fields is valid?

I created a sign-up pop up with HTML, CSS and JS. It validates data but the problem is that it sends(submits)data even if they are incorrect and redirects me to other page after submission, I dont want that. Also my email validation is not working.Please help: My code:

HTML
<div class="modal-content-right">
                <form action="https://www.w3schools.com/action_page.php" method="POST" class="modal-form" id="form">
                <h1>Register and start hunting! Create your account by filling out the information below.</h1>
                <div class="form-validation">
                    <input type="text" class="modal-input" id="name" name="name" placeholder="Enter your name">
                    <p>Error Message</p>
                </div>
                <div class="form-validation">
                   <input type="email" class="modal-input" id="email" name="email" placeholder="Enter your email">
                    <p>Error Message</p>
                </div>
                <div class="form-validation">
                    <input type="password" class="modal-input" id="password" name="password" placeholder="Enter your password">
                    <p>Error Message</p>
                </div>
                <div class="form-validation">
                    <input type="password" class="modal-input" id="password-confirm" name="password" placeholder="Confirm your password">
                    <p>Error Message</p>
                </div>
                <input type="submit" class="modal-input-btn" value="Sign-up">
                <span class="modal-input-login">Already have an account? Login <a href="#">here.</a></span>
                </form>

            </div>
Javasript
const form = document.getElementById('form');
const name = document.getElementById('name');
const email = document.getElementById('email');
const password = document.getElementById('password');
const passwordConfirm = document.getElementById('password-confirm');

//show error message
function showError(input, message) {
    const formValidation = input.parentElement;
    formValidation.className = 'form-validation error';

    const errorMessage = formValidation.querySelector('p');
    errorMessage.innerText = message;
}

function showValid(input) {
    const formValidation = input.parentElement;
    formValidation.className = 'form-validation valid';
}
//check required fields
function checkrRequired(inputArr) {
    inputArr.forEach(function(input) {
        if(input.value.trim() === '') {
            showError(input, `${getFieldName(input)} is required`);
        } else {
            showValid(input);
        }
    });
}
//get fieldname
function getFieldName(input) {
    return input.name.charAt(0).toUpperCase() + input.name.slice(1);
}
//check input

function checkLength(input, min, max) {
    if(input.value.length < min) {
        showError(input, `${getFieldName(input)} must be at least ${min} characters`);  
    } else if (input.value.length > max) {
        showError(input, `${getFieldName(input)} must be less than ${max} characters`);
    } else{
        showValid(input);
    }
}

//check if passwords match
function passwordMatch(input1, input2) {
    if(input1.value !== input2.value) {
        showError(input2, 'Passwords do not match');
    }
}
//event listeners
form.addEventListener('submit', (e) => {
    
    if(isFormValid()==true){
        form.submit();
    }else {
        e.preventDefault();
    }

    checkrRequired([name, email, password, passwordConfirm]);
    checkLength(name,4,30);
    checkLength(password, 8, 25);
    checkLength(passwordConfirm, 8, 25);
    passwordMatch(password, passwordConfirm);
});

I tried to create validated submit function, but was not succesfull.

function isFormValid() {
    const inputContainer = form.querySelectorAll('.form-validation');
    let result = true;
    inputContainer.forEach((container) => {
        if(container.classList.contains('error')) {
            result = false;
        }
    });
    return result;
}
function isFormValid() {
    const inputContainers = form.querySelectorAll('')
}

Call all the validation functions before you check for the validity of the entire form. You do not need to call form.submit when there are no errors; that will happen automatically.

form.addEventListener('submit', e => {
    checkrRequired([name, email, password, passwordConfirm]);
    checkLength(name,4,30);
    checkLength(password, 8, 25);
    checkLength(passwordConfirm, 8, 25);
    passwordMatch(password, passwordConfirm);
    if (!isFormValid()) e.preventDefault();
    // ...
});

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