3

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.**

2 Answers 2

2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/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;
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

store the value of your form fields in local var and validate var x=document.forms["myform"]["fname"].value;
1

Add an id to your fields and use getElementById

For the input value HTMLInputElement

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.