/ Published in: jQuery
Simple form validator
Just give your form the class validate and add the classes required or requiredEmail to the required input fields.
Expand |
Embed | Plain Text
(function($){ $(document).ready(function(){ $('form.validate').submit(function(){ var allPassed = true, msg = 'Niet alle verplichte velden zijn ingevuld, deze zijn rood gemarkeerd.', email_msg = 'Vul een geldig emailadres in aub', valid_bg = '#dff7dc', valid_bor = '1px solid #a0da9d', invalid_bg = '#e6b3b3', invalid_bor = '1px solid #bd4444'; // check if all required elements are filled in $(this).find('.required').each(function(){ if ($(this).val().trim() == "") { allPassed = false; $(this).css({ 'background-color' : invalid_bg, 'border' : invalid_bor }); } else { $(this).css({ 'background-color' : valid_bg, 'border' : valid_bor }); } }); // check if requiredEmail elements are filled in $(this).find('.requiredEmail').each(function(){ if ($(this).val().trim() === "") { allPassed = false; $(this).css({ 'background-color' : invalid_bg, 'border' : invalid_bor }); } else { var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; if(reg.test($(this).val()) == false) { allPassed = false; msg = email_msg; $(this).css({ 'background-color' : invalid_bg, 'border' : invalid_bor }); } else { $(this).css({ 'background-color' : valid_bg, 'border' : valid_bor }); } } }); if ( ! allPassed ) alert(msg); return allPassed; }); }); })(jQuery);
You need to login to post a comment.
