Wednesday 28 September 2016

Detect Mobile Device in JavaScript

To check the device is mobile or desktop in JavaScript, use the function given below
        function isMobile() {
            if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
                return true;
            }
            return false;
        }
    
To check the orientation of the device, check the width and height of the device.
        function isPortrait() {
            return window.innerHeight > window.innerWidth;
        }
    

Format the number in US Format in JavaScript

To get the number in US number format, we may use jQuery Globalization. But for a simple formatting like this, we may not need to include that library.
Just use the given function that will return number in the US format.
        function getFormattedNumber(number, isPrecision) {
            var isPrecision = typeof isPrecision != 'undefined' ? isPrecision : true; 
            if(isPrecision) {
                return number.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            } else {
                return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }
        }
    
If you don't need precision call the function with the precision false.
        getFormattedNumber(12345.25, false);
    
If the precision is need then set the precision with true or don't set that field, the default is true.
        getFormattedNumber(12345.25);
    

Desktop Notification for Web Application

Creating desktop nofications is really easy. We are going to use the Notification API of the browser to create the desktop notifications.
Before creating the notification its better to check whether the Notification API is supported in the browser.
To check the notification is supported simply check the typeof the Notification Object
        if(typeof Notification !== 'undefined'){
            // Create the notification
        } 
    
Once the Notification is exist, then its necessary to ask the permission from the user, only if the permission is granted we can able to create the notification. To get the permission from the user.
        Notification.requestPermission();
    
After the user grants permission, we can able to create the notification.
        if(Notification.permission == 'granted'){
            // Create notification
        }
    
To create the notification, create the instance of the Notification with the title and required options, here we are going to give the body of the notification with the icon
        var title = "Notification";
            var options = {
                body: "Notification Content",
                icon: "icon url"
            };
        var notification = new Notification(title, options);
    
To close the notification, you can call the close method of the Notification.
        notification.close();
    
To close the notification after some given time, say 5 seconds.
        setTimeout(notification.close(), 5000);
    
We can create a click listerner for the notification.
        notification.onclick = function(){
            console.log("notification clicked");
        }
    

Wednesday 21 September 2016

Jquery Validation for Stripe Payment

Jquery validation plugin can be used to validate simple forms, but for payment form involves credit/debit card number, cvc code we need to write a custom method to use efficiently.

There is Javascript library given by stripe to validate the fields like card number, cvc code. We can use this library to write our custom method in jQuery validation. Clone the jQuery.payment project from git and include the jquery.payment.min.js in your file.

To make the input box formatted we can use their format method.

For credit card number,
$('input.cc-num').payment('formatCardNumber');
For expiry dates
$('input.cc-exp').payment('formatCardExpiry');
For cvc code
$('input.cc-cvc').payment('formatCardCVC');
The payment html form will be like this,
<form action="" method="POST" id="payment-form" class="stripe-card">
  <div class="form-group">
     <label>Card Number</label>
     <input type="tel" size="20" data-stripe="number" class="form-control flat-control card-number cc-number" autocomplete="cc-number" name="cardnumber" placeholder="Card Number">
  </div>
  <div class="form-group">
     <label>Expiration (MM)</label>
     <input type="tel" size="2" data-stripe="exp_month" class="form-control flat-control card-expiry cc-exp" autocomplete="cc-exp" name="cardexpiry" placeholder="MM / YY">
  </div>
  <div class="form-group">
    <label>CVC</label>
    <input type="tel" size="4" data-stripe="cvc" class="form-control flat-control card-cvc cc-cvc" autocomplete="off" name="cardcvc" placeholder="CVC">
  </div>
  <div class="form-group">
    <input type="submit" class="btn btn-default" value="Submit" />
  </div>
</form>
Now, Let us write the custom jQuery validation methods for payment form.
$.validator.addMethod('cardNumber', function(value, element, param){
  return $.payment.validateCardNumber(value);
}, 'Invalid Card Number');

$.validator.addMethod('cardExpiry', function(value, element, param){
  return $.payment.validateCardExpiry(param);
}, 'Invalid Expiry Date');

$.validator.addMethod('cardCVC', function(value, element, param){
  return $.payment.validateCardCVC(value, param);
}, 'Invalid CVC Number');
Next, write the jQuery validation rules for the payment form.
var stripeCardPaymentForm = $('#payment-form');
  stripeCardPaymentForm.validate({
    debug: false,
    errorClass: "error-msg",
    errorElement: "small",
    rules: {
      cardnumber: {
        required: true,
        cardNumber: true
      },
      cardexpiry: {
        required: true,
        cardExpiry: function(element){
          return $(element).payment('cardExpiryVal');
        }
      },
      cardcvc: {
       required: true,
       cardCVC: function(element){
        return $.payment.cardType($(element).parents('.stripe-card').find('.card-number').val());
       } 
      }
    },
    messages: {
      cardnumber: {
        required: "Please Enter Card Number.",
        cardNumber: "Please Enter Valid Card Number."
      },
      cardexpiry: {
        required: "Please Enter Card Expiry Details.",
        cardExpiry: "Please Enter Valid Expiry Details."
      },
      cardcvc: {
       required: "Please Enter Card CVC Number.",
        cardCVC: "Please Enter Valid CVC Number."
     }
    },
    highlight: function(element, errorClass) {
      $(element).removeClass(errorClass);
    },
  });
And, that's it, now the jQuery validation is done for the form. We can check whether the form is valid or not by using
stripeCardPaymentForm.valid();
To perform the action when the form is valid,
if(stripeCardPaymentForm.valid()){  
// Do the success stuff, submit the form
} else {
  // Do the failure stuff, restrict the form submit
}