'Stop refresh after clicking submit form [duplicate]

Was trying to fill all the form before refreshing ! I mean if the name is wrong i dont want the page to refresh by hitting submit, i want it to wait until i fill all the inputs and they all go right !

I tried return false after every if statement but dosent work i tried e.preventDefault neither works ! Any help ?

            function validateForm(){
                var name = document.loginForm.name.value
                var email = document.loginForm.email.value
                var password = document.loginForm.password.value
                var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    
                if (name.length == 0)
                    return alert("Name wrong");
                else if (re.test(email) == false)
                    return alert('Enter a valid email');
                else if (password.length < 6)
                    return alert('password should be more than 6 characters');
                else 
                    return alert('Form submitted')
            }
    <div>
            <form action="" name="loginForm" onsubmit=validateForm()>
    
                <label for="">name</label>
                <input name="name" type="text">
                <label for="">email</label>
                <input name="email" type="email">
                <label for="">password</label>
                <input name="password" type="password">
                <button type="submit">Submit</button>
                <button type="reset">reset</button>
                
            </form>
        </div>
    


Solution 1:[1]

You need to prevent the default behavior of submitting a form using the event object. Inside your validateForm() function:

 function validateForm(e){
            e.preventDefault();
            ...
        }

Make sure you're taking the event object as a parameter inside the function. This will prevent the page from refreshing every time the form is submitted.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Siddhant Varma