简体   繁体   中英

Javascript form validation not displaying errors

just stuck on trying to get form validation to work. Before you say anything i am using jquery to pull files into a div, so the css file is in the index.php (not relevant here).

So i am trying to get some form validation here as i'm still learning here for university and i'm confused what is wrong here with the script to validate the form.

Oh and just a cookie question ... is it possible for when someone submits form but it throws an error that the content stays within the fields? or can i not because i'm using js to submit the form data?

Thanks to any replies :)

<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script language="javascript" type="text/javascript">
function validateForm(form){
var user=form.username.value;
var email = form.email.value;
var str=form.password.value;
var cstr=form.cpassword.value;
var err={}; 
var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
//check required fields
//checks username
if((user.length < 3) || (user.length > 15)){
err.message="username must be between 3 and 15 characters.";
err.field=form.username;
}
//password should be minimum 4 chars but not greater than 8
if ((str.length < 4) || (str.length > 8)) {
err.message="Invalid password length"; 
err.field=form.password; 
}
//check if repeated password matches
if(cstr!=str)
{
err.message="Passwords do not match";
err.field.form.cpassword;
}
//validate email
if(!(validemail.test(email))){
err.message="Invalid email"; 
err.field=form.email; 
}
if(err.message) 
        { 
               document.getElementById('results').innerHTML = err.message;
                err.field.focus();
                return false;                        
        } 
return true
}
</script> 
</head>
<body>
<div id="content" class="content">
    <div class="content-heading">
        <div class="content-heading-title">
        <h3>Register now!</h3>
        </div>
    </div>
    <div class="content-info">
    <form id="myForm" method="post" onsubmit="return validateForm(this);">
    Username:        <input name="username" id="username" type="text" /><br />
    Email:           <input name="email" id="email" type="text" /><br />
    Password:        <input name="password" id="password" type="password" /><br />
    Confirm Password:<input name="cpassword" id="cpassword" type="password" /><br /> 
    <input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
    </form>
    <div id="results"></div>
    </div>
</div>
    <script>
    function SubmitFormData() {
        var username = $("#username").val();
        var email = $("#email").val();
        var pass = $("#password").val();
        var cpass = $("#cpassword").val();
        $.post("submit.php", { 
            username: username, 
            email: email, 
            pass: pass,
            cpass: cpass
        }, function(data) {
            $('#results').html(data);
            $('#myForm').trigger('reset');
        });
    }
    </script>
</body>
</html>

Delete the onsubmit on your form and call validateForm from SubmitFormData .

You should do it like this:

function validateForm(){
    var username = $("#username").val();
    var email = $("#email").val();
    var pass = $("#password").val();
    var cpass = $("#cpassword").val();
    var err={
        message: "",
        field: ""
    }; 
    var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    //check required fields
    //checks username
    if(username.length < 3 || username.length > 15){
        err.message="username must be between 3 and 15 characters.";
        err.field="username";
    }
    //password should be minimum 4 chars but not greater than 8
    if (pass.length < 4 || pass.length > 8) {
        err.message="Invalid password length"; 
        err.field="password"; 
    }
    //check if repeated password matches
    if(cpass!=pass)
    {
        err.message="Passwords do not match";
        err.field="cpassword";
    }
    //validate email
    if(!validemail.test(email)){
        err.message="Invalid email"; 
        err.field="email"; 
    }
    if(err.message != "") 
    { 
        $("#results").html(err.message);
        $("#"+err.field).focus();
        return false;
    }
    $("#results").html(""); // to clean results div in the case of previous error message
    return true;
}

function SubmitFormData() {
    if(validateForm()) {
        var username = $("#username").val();
        var email = $("#email").val();
        var pass = $("#password").val();
        var cpass = $("#cpassword").val();
        $.post("submit.php", { 
            username: username, 
            email: email, 
            pass: pass,
            cpass: cpass
        }, function(data) {
            $('#results').html(data);
            $('#myForm').trigger('reset');
        });
    }
}
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<div id="content" class="content">
    <div class="content-heading">
        <div class="content-heading-title">
        <h3>Register now!</h3>
        </div>
    </div>
    <div class="content-info">
    <form id="myForm" method="post">
    Username:        <input name="username" id="username" type="text" /><br />
    Email:           <input name="email" id="email" type="text" /><br />
    Password:        <input name="password" id="password" type="password" /><br />
    Confirm Password:<input name="cpassword" id="cpassword" type="password" /><br /> 
    <input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
    </form>
    <div id="results"></div>
    </div>
</div>
    <script>
    function SubmitFormData() {
        var username = $("#username").val();
        var email = $("#email").val();
        var pass = $("#password").val();
        var cpass = $("#cpassword").val();
        var validemail = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

        if((username.length < 3) || (username.length > 15)) {       //Useranme should be minimum 3 chars but not greater than 15
            var message = "username must be between 3 and 15 characters.";
            $('#results').html(message);
            $("#username").focus();
            return false; 
        } else if ((pass.length < 4) || (pass.length > 8)) {        //password should be minimum 4 chars but not greater than 8
            var message = "Invalid password length"; 
            $('#results').html(message);
            $("#password").focus();
            return false;  
        } else if(cpass != pass) {      //check if repeated password matches
            var message = "Passwords do not match";
            $('#results').html(message);
            $("#cpassword").focus();
            return false; 
        } else if(email == "") {        //check if email address enterd
            var message = "Enter Email address";
            $('#results').html(message);
            $("#email").focus();
            return false; 
        } else if(!validemail.test(email)){     //validate email
            var message = "Invalid email"; 
            $('#results').html(message);
            $("#email").focus();
            return false;  
        } else { // Then POST the Form
            $('#results').html("Sending Registration");
            $.post("submit.php", { 
                username: username, 
                email: email, 
                pass: pass,
                cpass: cpass
            }, function(data) {
                $('#results').html(data);
                $('#myForm').trigger('reset');
            });
        }
    }
    </script>
</body>
</html>

Delete the onsubmit on your form and Delete the Validation function and put all validation in theSubmitFormData() function like above code

So many things to explain and flaws. But I extend from your code with small modification. Remaining you can understand and learn. Change as following:

    <html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script language="javascript" type="text/javascript">
function validateForm(form){

    var user=form.username.value;
    var email = form.email.value;
    var str=form.password.value;
    var cstr=form.cpassword.value;


    var err={}; 
    var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    //check required fields
    //checks username

    if((user.length < 3) || (user.length > 15)){
    err.message = "username must be between 3 and 15 characters.<br><br>";
    err.field=form.username;
    }

    //password should be minimum 4 chars but not greater than 8
    if ((str.length < 4) || (str.length > 8)) {
    err.message += "Invalid password length.<br><br>"; 
    err.field=form.password; 
    }
    //check if repeated password matches
    if(cstr!=str)
    {
    err.message += "Passwords do not match.<br><br>";
    err.field.form.cpassword;
    }
    //validate email
    if(!(validemail.test(email))){
    err.message += "Invalid email.<br><br>"; 
    err.field=form.email; 

    }
    if(err.message) 
    {  
           document.getElementById('results').innerHTML = err.message;
            err.field.focus();
            return false;                        
    } else {
        SubmitFormData();
        return false;
    }

}
</script> 
</head>
<body>
<div id="content" class="content">
    <div class="content-heading">
        <div class="content-heading-title">
        <h3>Register now!</h3>
        </div>
    </div>
    <div class="content-info">
    <form id="myForm" method="post" onsubmit="return validateForm(this);">
    Username:        <input name="username" id="username" type="text" /><br />
    Email:           <input name="email" id="email" type="text" /><br />
    Password:        <input name="password" id="password" type="password" /><br />
    Confirm Password:<input name="cpassword" id="cpassword" type="password" /><br /> 
    <input type="submit" id="submitFormData" value="Submit" />
    </form>
    <div id="results"></div>
    </div>
</div>
    <script>
    function SubmitFormData() {
        var username = $("#username").val();
        var email = $("#email").val();
        var pass = $("#password").val();
        var cpass = $("#cpassword").val();
        $.post("submit.php", { 
            username: username, 
            email: email, 
            pass: pass,
            cpass: cpass
        }, function(data) {
            $('#results').html(data);
            $('#myForm').trigger('reset');
        });
    }
    </script>
</body>
</html>

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