Monday 31 October 2016

Change Password Form In Angular 2

Angular 2 doesnt having validation for checking two fields having equal values, for that we need to create custom validation.
Lets create a change password form to demonstrate the custom validation for matching new password and confirm new password.
<div class="row">
    <div class="col-md-offset-3 col-md-6">
        <div class="panel panel-default">
            <div class="panel-body">
                <h2 class="text-center">Change Password</h2>
                <form [formGroup]="changePasswordForm" (ngSubmit)="changePassword(changePasswordForm.value)">
                    <div class="form-group" [ngClass]="{'has-error':!changePasswordForm.controls['old_password'].valid && changePasswordForm.controls['old_password'].touched}">
                        <label for="old_password">Old Password</label>
                        <input type="password" name="old_password" class="form-control" id="oldPassword" placeholder="Old Password" [formControl]="changePasswordForm.controls['old_password']" />
                        <small *ngIf="changePasswordForm.controls['old_password'].hasError('required') && changePasswordForm.controls['old_password'].touched" class="text-danger">Old Password Required</small>
                    </div>
                    <div class="form-group" [ngClass]="{'has-error':!changePasswordForm.controls['new_password'].valid && changePasswordForm.controls['new_password'].touched}">
                        <label for="new_password">New Password</label>
                        <input type="password" name="new_password" class="form-control" id="newPassword" placeholder="New Password" [formControl]="changePasswordForm.controls['new_password']" />
                        <small *ngIf="changePasswordForm.controls['new_password'].hasError('required') && changePasswordForm.controls['new_password'].touched" class="text-danger">New Password Required</small>
                    </div>
                    <div class="form-group" [ngClass]="{'has-error':!changePasswordForm.controls['confirm_new_password'].valid && changePasswordForm.controls['confirm_new_password'].touched}">
                        <label for="confirm_new_password">Confirm New Password</label>
                        <input type="password" name="confirm_new_password" class="form-control" id="newPassword" placeholder="Confirm New Password" [formControl]="changePasswordForm.controls['confirm_new_password']" />
                        <small *ngIf="changePasswordForm.controls['confirm_new_password'].hasError('required') && changePasswordForm.controls['c:onfirm_new_password'].touched" class="text-danger">Confirm New Required</small>
                        <small *ngIf="changePasswordForm.controls['confirm_new_password'].hasError('passwordMatch') && changePasswordForm.controls['confirm_new_password'].touched" class="text-danger">Password mismatch</small>
                    </div>
                    <div class="form-group text-center">
                        <button type="submit" class="btn btn-default" [disabled]="!changePasswordForm.valid">Change Password</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
Now, lets create a ts component for this
    import { Component } from '@angular/core';
    import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
    
    @Component({
      selector: 'change-password',
      templateUrl:'change-password.component.html',
      providers: [ UserService ]
    })
    
    export class ChangePasswordComponent {
    
        changePasswordForm:FormGroup;

        constructor(fb: FormBuilder){
            this.changePasswordForm = fb.group({
                'old_password': [null, Validators.required],
                'new_password': [null, Validators.required],
                'confirm_new_password': [null, [Validators.required, this.passwordMatch]] 
            });
        }
    
        passwordMatch(control: AbstractControl){
            let paswd = control.root.get('new_password');
            if(paswd && control.value != paswd.value){
             return {
                 passwordMatch: false
             };   
            }
            return null;
        }
    
        changePassword(value){
            if(this.changePasswordForm.valid){
                console.log("Change password form valid");
            }
        }
    
    }
    
Thats it, now register this component in the app module and use the selector <change-password></change-password> to see the change password form

Simple Login Form With Validation in Angular 2

Angular 2 having the form builder to build the login form with the validation, Here we see a simple login form with the validation.
Lets first create a html component with the user name and password form
<div class="row">
    <div class="col-md-offset-4 col-md-4">
        <div class="panel panel-default">
            <div class="panel-body">
                <h2 class="text-center text-muted">Login</h2>
                <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)">
                    <div class="form-group" [ngClass]="{'has-error':!loginForm.controls['user_name'].valid && loginForm.controls['user_name'].touched}">
                        <label for="username">User Name</label>
                        <input type="text" name="user_name" class="form-control" id="username" placeholder="User Name" [formControl]="loginForm.controls['user_name']" />
                        <small *ngIf="loginForm.controls['user_name'].hasError('required') && loginForm.controls['user_name'].touched" class="text-danger">Username Required</small>
                    </div>
                    <div class="form-group" [ngClass]="{'has-error':!loginForm.controls['password'].valid && loginForm.controls['password'].touched}">
                        <label for="password">Password</label>
                        <input type="password" name="username" class="form-control" id="password" placeholder="Password" [formControl]="loginForm.controls['password']" />
                        <small *ngIf="loginForm.controls['password'].hasError('required') && loginForm.controls['password'].touched" class="text-danger">Password Required</small>
                    </div>
                    <div class="form-group text-center">
                        <button type="submit" class="btn btn-default" [disabled]="!loginForm.valid">Login</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
The html component is created, now lets create the ts component for this form.
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'login-section',
  templateUrl:'login.component.html'
})

export class LoginComponent {
    loginForm: FormGroup;

    constructor(fb: FormBuilder){
        this.loginForm = fb.group({
            'user_name': [null, Validators.required],
            'password': [null, Validators.required]
        });
    }


    login(value){
        if(this.loginForm.valid){
           console.log("Login form valid");
        }        
    }
    
 }
Thats it, we have created the login form with validation, now register this component in the app.module and use the selector <login-section></login-section> to see the login form.

Monday 24 October 2016

Apply where condition if input exists in Laravel Eloquent ORM

If you want to apply multiple where condition based on whether particular inputs are present in laravel Eloquent ORM, we can use the array applied within the where.

Consider we are having the Movie table with its fields id, name, genre, year. we want to gets all movies list with or without genre and year.

public function getMovies($input) {
    $condition = array();
    if(!empty($input['genre'])){
        array_push($condition, ['genre', $input['genre']]);
    }
    if(!empty($input['year'])){
        array_push($condition, ['year', $input['year']]);
    }
    
    $result = Movie::where($condition)->get();
    return $result;
}

Thursday 20 October 2016

Checking Internet connection in web page using offline js

To check internet connection is active or not in the web page we can use the Offline.js plugin

Clone the git repository and include the offline.min.js file and any theme css file like offline-theme-slide.css with language css file offline-language-english.css

By default it will ping favicon.ico file in the server, we can customize it to any request

Offline.options = {checks: {image: {url: 'path/to/favicon/image'}, active: 'image'}}

To check the current status of the connection

Offline.check()

To check the current state of the connection 'up' or 'down'

Offline.state

To set event listener once connection is up

Offline.on('up', function(){
    console.log('Connection is up.');
});

To set event listener once connection is down

Offline.on('down', function(){
    console.log('Connection is down.');
});

Monday 3 October 2016

Jquery Validation For Masked Textbox

Jquery Validation cannot be used plainly for the masked textbox. To use Jquery validation for the masked textbox, we need to use Jquery validation addMethod to write custom method for adding validation for that masked textbox.

        
    $.validator.addMethod('numberForMasked', function(value, element, param){
        return !isNaN(value.replace(param, '').trim());
    }, "Ener only numbers");
    $.validator.addMethod("noDecimalForMasked", function(value, element, param) {
        return !(value.replace(param, '').trim() % 1);
    }, "No decimal numbers");
    $.validator.addMethod("minForMasked", function(value, element, param) {
        return value.replace(param[1], '').trim() >= param[0];
    }, "Number is too low");
    $.validator.addMethod("maxForMasked", function(value, element, param) {
        return value.replace(param[1], '').trim() <= param[0];
    }, "Number is too high");
    
Add rules for the masked text box in the form.

        
    var form = $("#form");
    form.validate({
        rules: {
            field: {
                required: true,
                numberForMasked: 'mask',
                noDecimalForMasked: 'mask',
                minForMasked: [1, 'mask'],
                maxForMasked: [999, 'mask']
            }
        },
        messages: {
            field: {
                required: "Please enter number",
                numberForMasked: "Please enter only numbers",
                noDecimalForMasked: "Please enter only integers",
                minForMasked: "Please enter atleast 1",
                maxForMasked: "Please enter less than 999"
            }
        }
    });
    
Here, mask is the text used for the masked text box, replace it with the text used in your masked textbox.

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
}