JavaScript Form Validation

情到浓时终转凉″ 提交于 2019-12-24 13:55:12

问题


I'm trying to create a form submission and before the form is submitted, I want to verify the credentials.

I have both this so far

HTML formatted for XHTML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
        <head>
            <title> Registration Form</title>
            <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
            <meta name="description" content="This is a form submission with validation"/>
            <script type="text/javascript" src="validScript.js"></script>
        </head>

        <body>
            <h1>Registration Form</h1>
            <form id="registration" action="" onsubmit="return validation();" method="post" enctype="text/plain">
                <p>Name: <input type="text" name="name" id="name"/></p>
                <p class="error">Email Address: <input type="text" name="emailAddress" id="emailAddress"/></p>
                <p><input type="submit" name="submit" value="Submit"/></p>
            </form>
        </body>

    </html>

JavaScript:

 function validation()
{  
    var vname = document.registration.name;

    if(nameValid(vname))
    {
        return true;
    }
    return false;
}

function nameValid(vname)
{
    var name_len = vname.value.length;
    if (name_len == 0)
    {
        alert("Name is required");
        vname.focus();
        return false;
    }
return true;
}

I'm having issues where it won't display alert the user that he/she prompted an empty name. I'm trying to valid the name and after this I'll add more functions for email address and other fields to be added. Note that this will later be used to email the form to a domain. Can someone help me figure out this problem?

Thanks


回答1:


your validation function is incorrect, should be:

function validation()
{  
    var vname = document.getElementById("name");

    if(nameValid(vname))
    {
        return true;
    }
    return false;
}

For access form elements values use document.getElementById("ElementID").value or use a javascript library like Jquery




回答2:


In form add name="registration" and then check. it will alert as you want.

and the reason is document.registration.name , where registeration is form name , not id.




回答3:


If you're using jQuery I can recommend this plugin:

http://validval.frebsite.nl/

I tried quite some validation plugins before I came to this one: It has extensive validation options and it's not too fancy on the dialogs; This means easy to customize the look and feel.



来源:https://stackoverflow.com/questions/15088538/javascript-form-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!