Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to validate form values using external javascript

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

<!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;
    }

}
like image 83
Pratap A.K Avatar answered Jul 14 '26 00:07

Pratap A.K


Add an id to your fields and use getElementById

For the input value HTMLInputElement

like image 29
Christophe Roussy Avatar answered Jul 14 '26 00:07

Christophe Roussy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!