admin管理员组

文章数量:1397142

Here I have created two fields one is for first name and another is for last name. Now how can I access these fields in external Javascript file and validate them.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Validation</title>
    </head>
    <body>
        <form action="something" method="post">
            FirstName:<input type="text" name="fname"/>
            LastName:<input type="text" name="lname"/>
            <input type="submit" value="submit">
        </form>
    </body>
</html>

I want to validate both First and last name using external Javascript file. how can i take the values to external Javascript file and validate. Please give me suggestions.

Thanks in advance.**

Here I have created two fields one is for first name and another is for last name. Now how can I access these fields in external Javascript file and validate them.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Validation</title>
    </head>
    <body>
        <form action="something" method="post">
            FirstName:<input type="text" name="fname"/>
            LastName:<input type="text" name="lname"/>
            <input type="submit" value="submit">
        </form>
    </body>
</html>

I want to validate both First and last name using external Javascript file. how can i take the values to external Javascript file and validate. Please give me suggestions.

Thanks in advance.**

Share Improve this question edited Jan 18, 2017 at 11:35 fernandosavio 10.4k4 gold badges26 silver badges34 bronze badges asked Oct 7, 2013 at 10:27 user2854201user2854201
Add a ment  | 

2 Answers 2

Reset to default 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Validation</title>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<form name="myform" action="something" onsubmit="return validateForm()" method="post">
FirstName:<input type="text" name="fname"/>
LastName:<input type="text" name="lname"/>
<input type="submit" value="submit">
</form>
</body>
</html>

and your java script file is(save as javascript.js)
function validateForm()
{
    var x=document.forms["myform"]["fname"].value;  
    if(x==null || x=="" )
    {
        alert("name can't be left blank");
        return false;
    }

    var y=document.forms["myform"]["lname"].value;
    if(y==null || y=="")
    {
        alert("last name is mandatory");
        return false;
    }
    else
    {
        return true;
    }

}

Add an id to your fields and use getElementById

For the input value HTMLInputElement

本文标签: htmlhow to validate form values using external javascriptStack Overflow