jQuery dynamic form validation -
working js fiddle :http://jsfiddle.net/dofpezeg/ dynamic form have apply validation.the problem facing when click on add button new fields created , validation doesnt run on them automatically.i have used each loop via ":input.req" req class name have given elements whether static or being created new. now, in onclick use this.val() checking empty space doesnt work new created fields.and when print value strored in "input.req.val()" picks value of first field through loop how can apply validation in way new fields validatd not empty regular expressions
$(document).on('click', '#btnac', function() { var empty = false; $(':input.req').each(function() { console.log($(':input.req').val()); var cbn = $('.newcbn').val(); var cba = $('.newcba').val(); var cban = $('.newcban').val(); var cbic = $('.newcbic').val(); var cuser = $('#cuser').val(); alert($(':input.req').val()); if ($(this).val() === '') { empty = true; } else if (/^[a-za-z ]+$/.test(cbn) === false) { empty = true; } else if (/^[a-za-z ]+$/.test(cba) === false) { empty = true; } else if (/^[0-9]+$/.test(cban) === false) { empty = true; } else if (/^[a-za-z]{4}\d{7}$/.test(cbic) === false) { empty = true; } else if (/^[0-9]+$/.test(cuser) === false) { empty = true; } else { empty = false; } }); if (empty) { $('#btnac').attr('disabled', 'disabled'); } else { $('#btnac').removeattr('disabled'); }
});
try code below, hope want.
$(document).on('click', '#btnac', function() { var empty = false; $(':input.req').each(function() { var val = $(this).val();// value of input on current loop index var $this = $(this); if (val === '') {// if value empty empty = true; } else if ($this.hasclass('newcbn')) {// test use different regexp according form input's class empty = !/^[a-za-z ]+$/.test(val); } else if ($this.hasclass('newcba')) { empty = !/^[a-za-z ]+$/.test(val); } else if ($this.hasclass('newcban')) { empty = !/^[0-9]+$/.test(val); } else if ($this.hasclass('newcbic')) { console.info(val) empty = !/^[a-za-z]{4}\d{7}$/.test(val); } else if ($this.attr('id') === 'cuser') {// test form $('#cuser') empty = !/^[0-9]+$/.test(val); } else { empty = false; } if (empty) {// if value didn't pass validate, break loop , disable button #btnac return false; } }); if (empty) { $('#btnac').attr('disabled', 'disabled'); } else { $('#btnac').removeattr('disabled'); } });
i use class of input determine regexp test value, , if value wrong, break $(':input.req').each()
loop, , disable button.
Comments
Post a Comment