JavaScript验证多个输入框

时间:2019-06-19 12:28:50

标签: javascript

我有以下HTML表单:

<div class="input_fields_wrap">
    <div class="form-group row">
        <label class="col-sm-3 col-form-label">Items</label>
        <div class="col-sm-7">
            <input type="text" name="items[]" class="form-control items" id="items">
        </div>
        <div class="col-sm-2">
            <button class="add_field_button btn btn-success btn-sm float-right">Add+</button>   
        </div>                      
    </div>
</div>

它具有 Add + 功能,基本上可以添加更多字段。因此,如果我添加更多字段,则该字段具有多个ID,:items,items1,item2等。

现在,在我的JavaScript验证功能中,我想检查个或多个项是否为空。

我可以检查一个字段,但是如何使用JavaScript检查多个字段?

一项字段的JavaScript验证代码:

var items           =   document.getElementById("items");
if (items.value == "") { 
    alert("Item name is reuired"); 
    items.focus(); 
    return false; 
}

用于Add +功能的JavaScript代码:

var max_fields      = 10; //maximum input boxes allowed
var wrapper         = $(".input_fields_wrap"); //Fields wrapper
var add_button      = $(".add_field_button"); //Add button ID

var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
    e.preventDefault();     
    if(x < max_fields){ //max input box allowed
        x++; //text box increment
        var form = '<div class="delete-row"><div class="form-group row"><label class="col-sm-3 col-form-label">Items</label><div class="col-sm-7"><input type="text" name="items[]" class="form-control items"></div><div class="col-sm-2"><a href="#" class="remove_field btn btn-danger btn-sm">( X )</a></div></div></div>';
        $(wrapper).append('<div>'+form+'</div>'); //add input box
    }
});

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); 
    $(this).parents('.delete-row').remove(); x--;
})    

完整验证码:

function validateForm () {

    var amount          =   document.forms["salesform"]["amount"];               
    var buyer           =   document.forms["salesform"]["buyer"];    
    var buyerRegex      =   /^[a-zA-Z0-9_ ]*$/;     
    var receipt_id      =   document.forms["salesform"]["receipt_id"];  
    var receiptIdRegex  =   /^[a-zA-Z_ ]*$/;        
    var items           =   document.querySelectorAll(".items");
    var itemsRegex      =   /^[a-zA-Z_ ]*$/;
    var buyer_email     =   document.forms["salesform"]["buyer_email"];  
    var note            =   document.forms["salesform"]["note"];  
    var city            =   document.forms["salesform"]["city"];  
    var phone           =   document.forms["salesform"]["phone"];
    var entry_by        =   document.forms["salesform"]["entry_by"];        


    if (amount.value == "") { 
        alert("Please enter the amount."); 
        amount.focus(); 
        return false; 
    } else if (isNaN(amount.value)) {
        alert("Amount should be only numeric value."); 
        amount.focus(); 
        return false; 
    }

    if (buyer.value == "") { 
        alert("Buyer name is required"); 
        buyer.focus(); 
        return false; 
    } else if (!buyerRegex.test(buyer.value)) {
        alert("Buyer name only contain letter, number and space."); 
        buyer.focus(); 
        return false; 
    } else if (buyer.value.length > 20 ) {
        alert("Buyer name must be less than 20 characters long."); 
        buyer.focus(); 
        return false; 
    }

    if (receipt_id.value == "") { 
        alert("Receipt Id is reuired"); 
        receipt_id.focus(); 
        return false; 
    } else if (!receiptIdRegex.test(receipt_id.value)) {
        alert("Receipt Id must contain only characters."); 
        receipt_id.focus(); 
        return false; 
    }

    items.forEach(ele => {  
        if (ele.value == "") {
            alert("Item name is required");
            ele.focus();// focuses on that particular input
            return false;
        }
    })

    return true;
}

4 个答案:

答案 0 :(得分:2)

您可以尝试执行以下操作,查询SelectorAll,因为forEach返回undefined,您可以尝试每个操作

const items = [...document.querySelectorAll("input[type=text]")];
items.every(ele => {
  //console.log(ele.value)
  if (ele.value == "") {
    alert("Item name is reuired");
    ele.focus();// focuses on that particular input
    return false; 
}
})
<div class="input_fields_wrap">
  <div class="form-group row">
    <label class="col-sm-3 col-form-label">Items</label>
    <div class="col-sm-7">
      <input type="text" name="items[]" class="form-control" id="items">
    </div>
    <div class="col-sm-2">
      <button class="add_field_button btn btn-success btn-sm float-right">Add+</button>
    </div>
  </div>
</div>

答案 1 :(得分:1)

这是Shubh回答的一个版本,但按班级查询。请务必注意,您无法通过从函数返回短路javascript中的forEach,因此我更改了此解决方案以使用for循环。有关更多信息,您可以阅读this SO question

let items = document.querySelectorAll(".items")
for (let i = 0; i < items.length; i++) {
  if (items[i].value == "") {
    alert("Item name is required");
    items[i].focus(); // focuses on that particular input
    return false;
  }
})
<div class="input_fields_wrap">
  <div class="form-group row">
    <label class="col-sm-3 col-form-label">Items</label>
    <div class="col-sm-7">
      <input class="items" type="text" name="items[]" class="form-control">
    </div>
    <div class="col-sm-2">
      <button class="add_field_button btn btn-success btn-sm float-right">Add+</button>
    </div>
  </div>
</div>

答案 2 :(得分:0)

我将输入字段更改为具有 item

class

然后我将循环所有这些项目。

ImportError: Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\ProgramData\Anaconda3\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:\ProgramData\Anaconda3\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: The specified module could not be found.


Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/errors

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

答案 3 :(得分:0)

在您的情况下,增加id的功能是完全没有用的。 getElementById将为您提供第一个匹配项。在您的情况下,要检查几个元素,明智的方法是使用QuerySelectorAll:

document.querySelectorAll('.form-control').forEach(node => {
    if(items.value == "") {
        ...
    }
})