javascript 如何在提交前使用javascript验证jsp中的表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21144420/
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 20:11:51  来源:igfitidea点击:

How to validate a form in jsp using javascript before submit

javascriptjqueryformsjspvalidation

提问by user123

<form name="Details" method="post" action="insertData.jsp" onSubmit="return ValidateForm();">
<label> Name </label > <input type="text" name="name" id="test1" > </input>
<label> ID </label > <input type="text" name="id" id="test2" > </input>
<label> Time </label > <input type="text" name="time" id="test3" > </input>
<label> Latitude </label > <input type="text" name="latitude" id="test4" > </input>
<label> Longitude </label > <input type="text" name="longitude" id="test5" > </input>
<input type= " submit" id="test6" value="submit" > </input>

Validation code in js

js中的验证码

function ValidateForm()
{
var uname=document.Detail.name;
if(alphanumeric(uname)){
}
return false;
}
function alphanumeric(uname){
var letter=/*[0-9a-zA-Z]+$/;
if(uname.value.match(letter)){
return true;
}
else{
aler("Enter both alpha and number");
uname.focus();
return false;
}
}

The above validation is to allow a textfield to accept both alphabets and numbers but not only numbers. Its returning false on a wrong input but still the data entered entered is submitted to the database. How to avoid this? what is wrong in my code?

上面的验证是允许文本字段接受字母和数字,但不仅仅是数字。它在错误输入时返回 false,但仍将输入的数据提交到数据库。如何避免这种情况?我的代码有什么问题?

I also want to validate form before submit. After every field is entered it should be validated and displayed if any error just below the field. How do i do it?

我还想在提交之前验证表单。输入每个字段后,应验证并显示该字段下方是否有任何错误。我该怎么做?

回答by Greg Burghardt

You could use a naming pattern for the Ids of hidden <span>tags that represent the form field error messages:

您可以为<span>表示表单字段错误消息的隐藏标签的 Id 使用命名模式:

<form onsubmit="return ValidateForm(this);">
    <p>
        <input type="text" id="name" name="name">
        <span style="display: none;" id="name-validation-message"></span>
    </p>
</form>

<script>
    function ValidateForm(form) {
        if (!alphanumeric(form.elements.name)) {
            var message = document.getElementById(form.elements.name.id + "-validation-message");
            message.innerHTML = "Must be alphanumeric";
            message.style.display = "";
        }
    }
</script>

The elementsproperty on formobjects is a key-value store where the keys are the values of the nameattribute on the form fields, and the values are either a reference to a single form field DOM node, or a collection.

对象elements上的属性form是一个键值存储,其中键是name表单字段上属性的值,这些值要么是对单个表单字段 DOM 节点的引用,要么是一个集合。

Consider the following HTML:

考虑以下 HTML:

<form id="test">
    <input type="text" name="foo">

    <input type="checkbox" name="bar" value="1">
    <input type="checkbox" name="bar" value="2">
    <input type="checkbox" name="bar" value="3">
    <input type="checkbox" name="bar" value="4">

    <input type="text" name="things[]">
    <input type="text" name="things[]">
    <input type="text" name="things[]">
    <input type="text" name="things[]">
    <input type="text" name="things[]">
    <input type="text" name="things[]">
    <input type="text" name="things[]">
</form>

We have three unique form field name attribute values:

我们有三个唯一的表单字段名称属性值:

  • foo
  • bar
  • things[]
  • 酒吧
  • 事物[]

In JavaScript, we'll have the following object model:

在 JavaScript 中,我们将拥有以下对象模型:

var form = document.getElementById("test");

form.elements; // A collection of references to all form fields

form.elements.foo; // Reference to <input type="text" name="foo">

// A DOM node collection referencing all checkboxes whose name is "bar"
form.elements.bar;
form.elements.bar[0]; // First "bar" checkbox
form.elements.bar[1]; // Second "bar" checkbox

// A DOM node collection referencing all text boxes whose name is "things[]"
form.elements["things[]"];
form.elements["things[]"][0]; // First "things[]" textbox
form.elements["things[]"][1]; // Second "things[]" textbox

Many server side languages turn field names with square brackets into arrays. You can access those fields in JavaScript using the Array Notation (e.g. form.elements["bar"]instead of Dot Notation (e.g. form.elements.bar).

许多服务器端语言将带有方括号的字段名称转换为数组。您可以使用数组表示法(例如,form.elements["bar"]而不是点表示法(例如form.elements.bar))在 JavaScript 中访问这些字段。

回答by Abhidemon

Hope the following code helps.

希望以下代码有所帮助。

<HTML>
  <HEAD>
    <TITLE>Verifying User Data</TITLE>
    <SCRIPT LANGUAGE="JavaScript">

        function checker()
        {
            var regExp1 = '/^(\d{1,2})\/(\d{1,2})\/(\d{2})$/' ;
            var result1 = document.form1.text1.value.match(regExp1);
            if (result1 == null || <*any other input doesnt satisfy the required format*>) {
                alert("Sorry, that's not a valid date.");
                document.form1.text1.focus(); // or document.<formname>.<element_name>.focus();
                return;
            } else {
                document.form1.action="<NextPage.jsp>" ;
                document.form1.method="GET"; // or "POST"
                document.form1.submit();

            }
        }

    </SCRIPT>
</HEAD>

<BODY>
    <H1>Verifying User Data</H1>
    <FORM NAME="form1"  >
        Please enter a date:
        <INPUT TYPE="TEXT" NAME="value1">
        <INPUT TYPE="<sometype>" NAME="value2">
        <INPUT TYPE="<sometype>" NAME="value3">
        ..
        ..
        <INPUT TYPE="button" onclick="checker()">
    </FORM>
</BODY>

回答by Deepak Singh

Write another javascript on submit button like

在提交按钮上编写另一个 javascript,如

          <input type= " submit" id="test6" value="submit" onclick="return save();"> 
  <script>
   function save(){
     document.form[0].submit;
        }
 </script>