Thursday, 6 March 2014

How to validate form using jQuery without plugin and submitHandler method

How to validate form using jQuery without plugin and submitHandler method 

Include jQuery validate library
i.e jquery.validate.js

1.How to ignore title in validation
$("#form").validate({
ignoreTitle: true
});

OR
$('#addUser').validate({
rules: {
'data[Member][password]': { 
 required: true,
 minlength: 6
},  
'data[Member][cnf_pass]': { 
required: true,
equalTo: '#password'
},
'data[Member][contact_no]': { 
number: true,
 },
messages: {  
                "data[Member][contact_no]": { 
number: 'Only Numeric Value.'
 } 
            }  
       }
      });

Email validation unique
$("#email").rules('add',{remote:ajax_url+'Members/check_email',
messages: {remote: "Email address already exist"}});

Password validation  
$("#Password").rules('add',{minlength: 6,
messages: {minlength: "Password should be atleast 6 characters long."}});
Confirm Password 
$("#confirm_password").rules('add',{equalTo: "#Password",

messages: {equalTo: "Password and confirm password do not match"}});

2.Want Credit card validation
var handleValidation3 = function() {
var form1 = $('#payment-options');
var error1 = $('.alert-danger', form1);
var success1 = $('.alert-success', form1);
form1.validate({
errorElement: 'span', 
errorClass: 'help-block',
focusInvalid: false, 
ignore: "",
rules: {
name_on_card: {
minlength: 2,
required: true
},
card_number: {
creditcard: true,
required: true
},
card_expiry_date: {
minlength: 2,
required: true,
remote:"index.php"
},
cvv: {
minlength: 3,
maxlength: 4,
number:true,
required: true
}
},
invalidHandler: function (event, validator) { 
//display error alert on form submit              
success1.hide();
error1.show();
App.scrollTo(error1, -200);
},
highlight: function (element) { 
// hightlight error inputs
// set error class to the control group
$(element).closest('.form-group').addClass('has-error'); 
},
unhighlight: function (element) { 
// revert the change done by hightlight
// set error class to the control group
$(element).closest('.form-group').removeClass('has-error'); 
},
success: function (label) {
// set success class to the control group
label.closest('.form-group').removeClass('has-error'); 
},
submitHandler: function (form) {
form.submit(); 
}
});
jQuery(document).ready(function() {    
handleValidation3();
});

3. Validate form by jquery without validate plugins
Html:
<div class="relative">
<input type="text" class="form-input required" id="first_name" name="first_name"/>
</div>
<div class="relative">
<input type="text" class="form-input required" id="last_name" name="last_name"/>
</div>
<div class="relative">
<input type="email" class="form-input required" id="email" name="email" />
</div>
<div class="relative">
<input type="text" class="form-input required" id="city" name="city"/>
</div>
jquery
$("#QiuckContactForm").on('submit', function(e) {
e.preventDefault();
var _formCanSubmit = true;
var _emailPattern = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+\.([a-zA-Z0-9]{2,4})$/;
var __message = "<span class='_error' style='color:#E00'>This field is required</span>";
var __emailMessage = "<span class='_error' style='color:#E00'>Please enter valid email.</span>";
var __phoneMessage = "<span class='_error' style='color:#E00'>Please enter valid phone number.</span>";
$(this).find('input.required').each(function(k, ele){
if($(ele).parent('div').find('span._error').length>0){
$(ele).parent('div').find('span._error').remove();
$(ele).addClass('field-error');
_formCanSubmit=false;
}
if($(ele).val().trim() == ''){
if($(ele).parent('div').find('span._error').length==0){
$(ele).parent('div').append(__message);
$(ele).addClass('field-error');
_formCanSubmit=false;
}
}else if($(ele).attr('type')=='email') {
if (!_emailPattern.test($(ele).val())) {
$(ele).parent('div').append(__emailMessage);
$(ele).addClass('field-error');
_formCanSubmit=false;
}
}else if($(ele).hasClass('captcha')) {
if ($(ele).val().trim()=='') {
$(ele).parent('div').append(__message);
$(ele).addClass('field-error');
_formCanSubmit=false;
}
}
});
if($('input#phone').val().trim() !=''){
var data = $('input#phone').val();
if(isNaN(data)){
$('input#phone').parent('div').append(__phoneMessage);
$('input#phone').addClass('field-error');
_formCanSubmit=false;
}
}
if (_formCanSubmit==true) {
$(this).submit();
}
});
Validation on keyup
$(document).on('keyup', 'input.required', function(){
var _emailPattern = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+\.([a-zA-Z0-9]{2,4})$/;
var __emailMessage = "<span class='_error' style='color:#E00'>Please enter valid email.</span>";
if($(this).hasClass('field-error')){
$(this).parent('div').find('span._error').remove();
$(this).removeClass('field-error');
}
if($(this).val().trim() == ''){
var __message = "<span class='_error' style='color:#E00'>This field is required</span>";
if($(this).parent('div').find('span._error').length==0){
$(this).parent('div').append(__message);
$(this).addClass('field-error');
}
}else if($(this).attr('type')=='email') {
if(!_emailPattern.test($(this).val())) {
$(this).parent('div').append(__emailMessage);
$(this).addClass('field-error');
}
}
});

Use Custom method for Age validation
function get_age(born, now) {
      var birthday = new Date(now.getFullYear(), born.getMonth(), born.getDate());
      if (now >= birthday)
return now.getFullYear() - born.getFullYear();
      else
        return now.getFullYear() - born.getFullYear() - 1;
}
var year=$(".year").val();
var month=$(".month").val();
var day=$(".day").val();
if(day=="" || month=="" || year==""){
     alert("Please select your date of birth.");
     return false;
} else{
     var now = new Date();
     var born = new Date(year, month, day);
     age=get_age(born,now);
     if (age<13){
alert("You need to be 13 years of age and older!");
return false;
    }

}

0 comments:

Post a Comment