如何使用外部 javascript 验证表单值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19222414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:48:04  来源:igfitidea点击:

how to validate form values using external javascript

javascripthtmlvalidation

提问by

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.

在这里,我创建了两个字段,一个用于名字,另一个用于姓氏。现在如何访问外部 Javascript 文件中的这些字段并验证它们。

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

我想使用外部 Javascript 文件验证名字和姓氏。我如何将值带到外部 Javascript 文件并进行验证。请给我建议。

Thanks in advance.**

提前致谢。**

采纳答案by Pratap A.K

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

}

回答by Christophe Roussy

Add an id to your fields and use getElementById

将 id 添加到您的字段并使用getElementById

For the input value HTMLInputElement

对于输入值HTMLInputElement