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...

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]');

How to replace plain URLs with links

Here we will explain how to replace Urls with links from string Using PHP $string ='Rajiv Uttamchandani is an astrophysicist, human rights activist, and entrepreneur. Academy, a nonprofit organization dedicated to providing a robust technology-centered education program for refugee and displaced youth around the world.  CNN Interview - https://www.youtube.com/watch?v=EtTwGke6Jtg   CNN Interview - https://www.youtube.com/watch?v=g7pRTAppsCc&feature=youtu.be'; $string = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $string); Using Javascript <script> function linkify(inputText) {     var replacedText, replacePattern1, replacePattern2, replacePattern3;     //URLs starting with http://, https://, or ftp://     replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;     replacedText = inputT...