Skip to main content

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;
    }

}

Comments

Popular posts from this blog

Generate XML file in Cakephp

Steps to Generate XML file using CakePHP: Step-1 Enable to parse xml extension in config route.php file.     Router::parseExtensions('xml'); Step-2 Add Request Handler Component to the Controller    var $components = array(‘RequestHandler’); Step-3 Add controller Action For XML Generation in Post Controller     function generateXMLFile()     {         if ($this->RequestHandler->isXml()) { // check request type             $this->layout = 'empty'; // create an empty layout in app/views/layouts/empty.ctp              }        }  Add header code in empty layout <?php header('Content-type: text/xml');?> <?php echo $this->Xml->header(); ?> <?php echo $content_for_layout; ?> Step-4 Set up View To generate XML Create xml folder inside Posts vi...

Simple JavaScript Object and Class Examples

In JavaScript, most things are objects. An object is a collection of related data and/or functionality Namespace: Everything you create in JavaScript is by default global. In JavaScript namespace is Global object . How to create a namespace in JavaScript? Create one global object, and all variables, methods, and functions become properties of that object. Example:  // global namespace var MYAPP = MYAPP || {}; Explaination: Here we first checked whether MYAPP is already defined.If yes, then use the existing MYAPP global object, otherwise create an empty object called MYAPP How to create sub namespaces? // sub namespace MYAPP.event = {}; Class JavaScript is a prototype-based language and contains no class statement.JavaScript classes create simple objects and deal with inheritance. Example: var Person = function () {}; Explaination: Here we define a new class called Person with an empty constructor. Use the class keyword class Calculation {}; A class expr...

How to Add Next Previous links to The Event Calendar

Add Next/Previous links to The Event Calendar Wordpress Plugin Add code to your child theme’s functions.php file /**  * Allows visitors to page forward/backwards in any direction within month view */ if ( class_exists( 'Tribe__Events__Main' ) ) { class ContinualMonthViewPagination {     public function __construct() {         add_filter( 'tribe_events_the_next_month_link', array( $this, 'next_month' ) );         add_filter( 'tribe_events_the_previous_month_link', array( $this, 'previous_month' ) );     }     public function next_month() {         $url = tribe_get_next_month_link();         $text = tribe_get_next_month_text();         $date = Tribe__Events__Main::instance()->nextMonth( tribe_get_month_view_date() );         return '<a data-month="' . $date . '" href="' . $url . '" rel="next"...