Jquery / Forms / Form validation
Form Validation
-
STEPS
1. Solution 1 : get one by one using id or class
in view, add id to each field
in jquery
1. get value of fields using id
2. check value is null
3. if error==1 , show error message
4. if error ==0, submit form$("#btn_save").click(function(){ var error=0; var name=$('#name').val(); var email=$('#email').val(); var mobile=$('#mobile').val(); if(name==''){ error=1; } if(email==''){ error=1; } if(mobile==''){ error=1; } if(error==1){ alert("Please fill mandatory fields"); return false; } else{ $('#frm_reg').submit(); return true; } }); 2. Solution 2 : dynamic validation
in view, add 'mandatory' class to each field instead of id
in jquery
$("#btn_save").click(function(){ var error=0; $('.mandatory').each(function(index, obj){ if(obj.value==''){ error=1; } }); if(error==0){ $("#frm_reg").submit(); } else{ alert("Please fill mandatory fields"); return false; } }); Advanced options
Validatioon based on input type
Yes No NA$( "#btn_save" ).click(function() { var error=0; $('.mandatory').each(function(index, obj){ switch(obj.type){ case 'radio': if ($('input[name='+ obj.name +']:checked').length > 0) { } else{ $(obj).parent().parent().find('.errormessage').show(); $(obj).parent().parent().find('.errormessage').text($(obj).data('message')); error=1; } break; default: if(obj.value==''){ //alert($(obj).data('message')); $(obj).next('.errormessage').show(); $(obj).next('.errormessage').text($(obj).data('message')); error=1; } break; } }); if(error==0){ $( "#frm_ticket" ).submit(); } }); switch(obj.type) is used to identify the input type Alert styling
in view
in css