how to validate form values using external javascript
12,996
Solution 1
<!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;
}
}
Solution 2
Add an id to your fields and use getElementById
For the input value HTMLInputElement
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 07, 2022Comments
-
Admin about 2 years
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.**