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

A Guide to UTF-8 for PHP and MySQL

Data Encoding: A Guide to UTF-8 for PHP and MySQL As a MySQL or PHP developer, once you step beyond the comfortable confines of English-only character sets, you quickly find yourself entangled in the wonderfully wacky world of UTF-8. On a previous job, we began running into data encoding issues when displaying bios of artists from all over the world. It soon became apparent that there were problems with the stored data, as sometimes the data was correctly encoded and sometimes it was not. This led programmers to implement a hodge-podge of patches, sometimes with JavaScript, sometimes with HTML charset meta tags, sometimes with PHP, and soon. Soon, we ended up with a list of 600,000 artist bios with double- or triple encoded information, with data being stored in different ways depending on who programmed the feature or implemented the patch. A classical technical rat’s nest.Indeed, navigating through UTF-8 related data encoding issues can be a frustrating and hair-pul...

How To Create Shortcodes In WordPress

We can create own shortcode by using its predified hooks add_shortcode( 'hello-world', 'techsudhir_hello_world_shortcode' ); 1. Write the Shortcode Function Write a function with a unique name, which will execute the code you’d like the shortcode to trigger: function techsudhir_hello_world_shortcode() {    return 'Hello world!'; } Example: [hello-world] If we were to use this function normally, it would return Hello world! as a string 2. Shortcode function with parameters function techsudhir_hello_world_shortcode( $atts ) {    $a = shortcode_atts( array(       'name' => 'world'    ), $atts );    return 'Hello ' . $a['name'] . !'; } Example: [hello-world name="Sudhir"] You can also call shortcode function in PHP using do_shortcode function Example: do_shortcode('[hello-world]');

Integrating Kafka with Node.js

Integrating Kafka with Node.js Apache Kafka is a popular open-source distributed event streaming platform that uses publish & subscribe mechanism to stream the records(data). Kafka Terminologies Distributed system: Distributed system is a computing environment where various software components located on different machines (over multiple locations). All components coordinate together to get stuff done as one unit.   Kafka Broker: Brokers are cluster of multiple servers. Message of each topic are split among the various brokers. Brokers handle all requests from clients to write and read events. A Kafka cluster is simply a collection of one or more Kafka brokers. Topics: A topic is a stream of "related" messages. Its unique throughout application. Kafka producers write messages to topics. Producer: Producer publishes data on the topics. A producer sends a message to a broker and the broker receives and stores messages. Consumers: Consumers read data from topics. A consu...