开发者

Javascript validation on multiple input controls

i have arrays of input controls and want to check o开发者_JS百科n submit that they should not be empty


Here's an example function:

function valid( array ) {
   if( typeof array != 'object' || array.length < 1 ) return false; // some basic error checking
   var errors = [];
   var alen = array.length;
   for( var a = 0; a < alen; a++ ) {
       if( array[ a ].value.length < 1 ) errors.push( array[ a ] );
   }
   if( errors.length >= 1 ) return errors;
   return true;
}

Usage:

function submitForm() {
   var inputs = document.getElementsByTagName( 'input' );

   var errors = valid( inputs );
   if( errors ) {
        var elen = errors.length;
        for( var e = 0; e < elen; e++ ) {
           errors[ e ].className = "error";
        }
        event.preventDefault();
        return false;
   }
}

var form = document.getElementById( 'myForm' ).onsubmit = submitForm;

If you were using a framework, this would be even easier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜