jQuery 如何使用分配给表单的 ID 使用 JavaScript 验证空/空字段的 html 表单

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

How to validate html form for null/empty fields with JavaScript using ID assigned to form

javascriptjqueryhtmlformsvalidation

提问by irm

I'm trying to validate my html form with JavaScript as so it iterates trough out all input fields and checks for empty/null fields.

我正在尝试使用 JavaScript 验证我的 html 表单,因为它会遍历所有输入字段并检查空/空字段。

I found a way to validate for null on w3s (code below) but I want to modify the function as so it checks for all fields on the form using a specific idthat I have assigned to the entire form, instead of only targeting one field.

我找到了一种在 w3s 上验证 null 的方法(下面的代码),但我想修改该函数,以便它使用id我分配给整个表单的特定字段来检查表单上的所有字段,而不是仅针对一个字段。

function validateForm() {
   var x = document.forms["myForm"]["fname"].value;
   if ( x == null || x == "" ) {
      alert("First name must be filled out");
      return false;
   }
}
</script>
</head>

<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
    First name: <input type="text" name="fname">
    <input type="submit" value="Submit">

回答by Crouch

As well as these I would include the requiredattribute, just incase users have javascript disabled.

除了这些,我还会包括required属性,以防万一用户禁用了 javascript。

<input type="text" id="textbox" required/>

It works on all modern browsers not the older ones though as it is part of HTML 5

它适用于所有现代浏览器而不是旧浏览器,因为它是 HTML 5 的一部分

回答by dbanet

function validateForm(formId){
    var form=document.getElementById(formId);
    for(i=0; i<form.childNodes.length; i++)
        if(form.childNodes[i].tagName!='INPUT'||
           typeof form.childNodes[i].value=="undefined")
            continue;
        else{
            var x=form.childNodes[i].value;
            if(x==null||x==""){
                alert("First name must be filled out");
                return false;
            }
        }
}

Not sure if it works.

不确定它是否有效。

回答by qais

It's been a while since you posted this question, but since you haven't accepted an answer, here's a simple solution: (jsfiddle)

你发布这个问题已经有一段时间了,但由于你还没有接受答案,这里有一个简单的解决方案:( jsfiddle)

function Validate()
{
    var msg= "",
        fields = document.getElementById("form_id").getElementsByTagName("input");

    for (var i=0; i<fields.length; i++){
        if (fields[i].value == "") 
            msg += fields[i].title + ' is required. \n';
    }

    if(msg) {
        alert(msg);
        return false;
    }
    else
        return true;
}

回答by fabio

give the form an id of "myForm"

给表单一个“myForm”的id

then you can select it with: var form = document.getElementById("myForm");

然后你可以选择它: var form = document.getElementById("myForm");

回答by Satyam Saxena

Here is the simplest way:

这是最简单的方法:

<script>
        function validateForm(formId)
        {
            var inputs, index;
            var form=document.getElementById(formId);
            inputs = form.getElementsByTagName('input');
            for (index = 0; index < inputs.length; ++index) {
                // deal with inputs[index] element.
                if (inputs[index].value==null || inputs[index].value=="")
                {
                    alert("Field is empty");
                    return false;
                }
            }
        }
</script>

Replace <form> tag with the below:

将 < form> 标签替换为以下内容:

<form name="myForm" id="myForm" action="1.php" onsubmit="return validateForm('myForm');" method="post">

回答by Mehul Jariwala

just put the Required into the input tag then whenever you click the submit button then empty Textbox will give the error field can not blank. example:- <input type="text" id="textbox" required/>

只需将 Required 放入输入标签,然后每当您单击提交按钮时,空文本框都会使错误字段不能为空。例子:- <input type="text" id="textbox" required/>

回答by Patrik

It is important to manage the fact that for some form elements like textareas, the required attribute behaves in Firefox differently from all other browsers. In Firefox whether your input is NULL or empty, the required attribute block the form submission. But in Chrome or Edge, the form will submit on an empty field not on NULL one

管理这样一个事实很重要,即对于像 textareas 这样的一些表单元素, required 属性在 Firefox 中的行为与所有其他浏览器不同。在 Firefox 中,无论您的输入是 NULL 还是空, required 属性都会阻止表单提交。但是在 Chrome 或 Edge 中,表单将提交一个空字段而不是 NULL 字段