简体   繁体   中英

How do I Validate Arrays?

I have a form which has 4 columns and the user can dynamically add or delete rows. Now I tried to validate this through javascript following code:-

<script type="text/javascript">
function chkempty()
        {


    var x=document.forms["main"]["qty[]"].value
    var y=document.forms["main"]["price[]"].value
    var z=document.forms["main"]["item[]"].value
    if (x==null || x=="")   {
                            alert("Quantity must be filled out");
                            return false;
                            }
    if (y==null || y=="")   {
                            alert("Price must be filled out");
                            return false;
                            }
    if (z==null || z=="")   {
                            alert("Itemcode cannot be empty");
                            return false;
                            }   
        }

It works for the first row but when the user selects more than one row, even after filling up values, he is getting the validation error message. can someone help me with this please? Thanks and keep smiling.

var x=document.forms["main"]["qty[]"].value

You should loop over the elements and validate each value, instead of trying to get a value from an array, I guess.

 var x=document.forms["main"]["qty"];
 for ( var i=0, len=x.length; i<len; ++i ){
    // validate the value of the current element.
 }

EDIT : added a small example.

document.forms.form_id.control_name will return either an HTMLElementNode or a NodeList depending if there are one or many matching elements.

You can do something like:

var x=document.forms["main"]["qty[]"]
if (x.nodeName) {
    // Is a Node. Work with its value
} else {
    // Is a NodeList, loop over it with for
    for (var i = 0; i < x.length; i++) {
        var node = x[i];
        // Work with its value
    }
}

VERY simple solution here:

Use Jquery Inline Validator

When you add new lines of content to the table, simply ensure that you have the proper class defined (such as class="validate[required,custom[email]]" ) to ensure that it will validate the field correctly as you wish. I often just do the required element, but the example I gave above also does email format checking. There are additional built in checkers for phone numbers, currency, etc.

If the user messes up an input, it will display a visually appealing tooltip like dialog next to the field with the error.

Done. Simple. Clean. Fast.

None of these solutions make up for the fact that you really need to sanitize on the server-side as well. Any Javascript can be bypassed, so it's not 100% guaranteed to be safe or accurate. But it is a good start and provides quality, instant feedback to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM