Tuesday, 27 December 2016

Render partial view


View(normal view)
@model HoleObject

<div id="add">
@Html.Partial("_add", Model.Add)//add
</div>
<div id="list">
@Html.Partial("_list", Model.ListObj)//display the list
</div>

<script>
 $("#Add").on("submit", "form", function (e) {
                    $(".js-loading").removeClass("hide");
                    e.preventDefault();
                   var form =new FormData($(this)[0])
                   // var form = $(this);
                    $.ajax({
                        url: 'localhost/Add',
                        type: "POST",
                        data: form.serialize(),
                        success: function (response) {
                            if (response.Errors != null && response.Errors != '') {
                               alert(response.Errors)
                            }
                            else {
                                getList ();
                            }
                        },
                        error: function (errorcode, textStatus, errorThrown) {
                            alert("Error '" + errorcode.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                        },
                        complete: function () {
                            $(".js-loading").addClass("hide");
                        }
                    });
                });
var getList = function () {
                $.ajax({
                    url: 'localhost/List',
                    data: { id: '@Model.Id' },
                    type: "GET",
                    success: function (html) {
                        if ($.trim(html) != '') {
                            $("#list").html('');
                            $("#list").html(html);
                            $(".js-loading").removeClass('hide');
                        }
                    }
                });
            }
            getList ();
<script>

-------------------------------------------------------------------------------------------------------------------------
//controller
public PartialViewResult Add(int id)
        {
            var model = new Add();
            try
            {
                   if(id!=0)
                          model=ExistData where id==id//get existing data for edit

            }
            catch (Exception ex)
            {
                ex.LogException();
            }
            return PartialView("_add", model);

        }
[HttpPost]
public JsonResult Add(Add model)
        {
            if (!ModelState.IsValid)
                return AsError();
            try
            {
               
                       //insert into db

            }
            catch (Exception ex)
            {
                ex.LogException();
            }
            return Json("success")

        }

public PartialViewResult List()
        {
            var model = new List<ListObj>();
            try
            {
                  model   =getlist from db.ToList();
             }
            catch (Exception ex)
            {
                ex.LogException();
            }
            return PartialView("_list", model);

        }

Tuesday, 20 December 2016

Data annotation validation for email ID in C#

//For all kind of emails it can validate like example.123@example.com, .com.in,.co.in etc

[RegularExpression("^$|^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9]+‌​)*\\.([a-z]{2,})(\\.([a-z]{2,4}))?$", ErrorMessage = "The email field is not a valid e-mail address.")]

Console 404 error resolved for(.json, .woff, .woff2)

Put this contents in web config.
<staticContent>
      <mimeMap fileExtension=".json" mimeType="Content-Type: application/json" />
      <mimeMap fileExtension=".woff" mimeType="Content-Type: application/font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="Content-Type: application/font-woff2" />
    </staticContent>

Thursday, 15 December 2016

Prevent form submission on enter key

<script>
    document.getElementById("FormId").onkeypress = function (e) {
        var key = e.charCode || e.keyCode || 0;
        if (key == 13) {
            e.preventDefault();
        }
    }
</script>

Friday, 18 November 2016

Confirmation alert before close browser Tab

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
        window.onbeforeunload = function (e) {
            e =  window.event;
            // For IE and Firefox prior to version 4
            return false;
            if (e) {
                e.returnValue = 'Any string';
            }

            // For Safari
            return 'Any string';
        };

        $(function () {
            $(".btn3").click(function (e) {
                window.onbeforeunload = null;//after click this button alert not showm
            });
        });
    </script>
</head>
<body>
           <form action="#" method="get">
                <input type="submit" value="submit" class="btn" />
            </form>
            <input class="btn btn1" type="button" value="btn1" />
            <input class="btn btn2" type="button" value="btn2" />
            <input class="btn btn3" type="button" value="btn3" />
</body>
</html>

Thursday, 3 November 2016

Login failed for user 'NT AUTHORITY\SYSTEM'

Steps:
1.Open IIS ->Application Pools -> DefaultAppPool -> Advanced Settings ->
set
Identity=ApplicationPoolIdentity

2.Restart IIS

3.Now try with application.

Sunday, 30 October 2016

SQL Database Authentication error while using Entity Framework(Solved)

Db Authentication error

1.Open SQL Server Management Studio

2.Db -> Security -> Logins -> BUILTIN\Users -> right click -> Properties -> Server Roles -> select the options you want -> click ok

3.Now try with application.

Wednesday, 5 October 2016

Difference between Convert and Parse

Both int.Parse and Convert.ToInt32 are used to convert string into the integer but Only difference between them is to Convert.ToInt32 handle null and returns '0' as output and int.parse is not going to handle NULL and will give a Argument Null Exception

  • If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse().
  • If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters in invalid input.
  • Convert.ToInt32() takes an object as its argument, and I believe it invokes Int32.TryParse()when it finds that the object taken as the argument is a string.
    Convert.ToInt32() also does not throw ArgumentNullException when it's argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.

Hash Set best example in C#

Example Here
HashSet is an optimized set collection. It helps eliminates duplicate strings or elements in an array. It provides a simple syntax for taking the union of elements in a set. This is performed in its constructor.

C# program that uses HashSet on duplicates

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
 // Input array that contains three duplicate strings.
 string[] array1 = { "cat", "dog", "cat", "leopard", "tiger", "cat" };

 // Display the array.
 Console.WriteLine(string.Join(",", array1));

 // Use HashSet constructor to ensure unique strings.
 var hash = new HashSet<string>(array1);

 // Convert to array of strings again.
 string[] array2 = hash.ToArray();

 // Display the resulting array.
 Console.WriteLine(string.Join(",", array2));
    }
}

Output

cat,dog,cat,leopard,tiger,cat
cat,dog,leopard,tiger

Monday, 3 October 2016

Run and install ASP through CMD prompt.(IIS error 500.21 solved)

This issue can be resolved by using one of the following method:

Method 1: Enable the Directory Browsing feature in IIS (Recommended)

To resolve this problem, follow these steps:
  1. Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
  2. In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
  3. In the Features view, double-click Directory Browsing.
  4. In the Actions pane, click Enable.

Method 2: Add a default document

To resolve this problem, follow these steps:
  1. Start IIS Manager. To do this, click Start, click Run, type inetmgr.exe, and then click OK.
  2. In IIS Manager, expand server name, expand Web sites, and then click the website that you want to modify.
  3. In the Features view, double-click Default Document.
  4. In the Actions pane, click Enable.
  5. In the File Name box, type the name of the default document, and then click OK.

Example here
//while using IIS enable Directory Browsing

steps:
1.Open CMD prompt run as admin mode

2.CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319\
*press enter
3.aspnet_regiis -i
*press enter

Wednesday, 21 September 2016

Html title content next line

<div class="form-group" title="item 1 &#013; item2 &#013; item3">
</div>

Simulating multiple dropdown list with check box in MVC Entity frame work

 Model
 public class ViewModelClass
{
 public List<CheckBoxList> checkBoxList{ get; set; }
}
public class CheckBoxList
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsChecked { get; set; }
    }

Controllers
 public async Task<ActionResult> Create()
{
ViewModelClass model=new ViewModelClass();
model.checkBoxList=.db.fromTable.AsEnumerable().Select(x => new CheckBoxList()
              {
                    Id = x.Id,
                    Name = x.Name,
                    IsChecked = false,//first time creating so false
                }).ToList();
return view(model)
 }
VIEW
<style>
.dropdown-div
{
    overflow-y:scroll !important;
    height:100px !important;
    width:280px !important;
    padding-top: 6px;
    padding-right: 12px;
    padding-bottom: 6px;
    padding-left: 12px;
}
</style>
 <div class="form-control dropdown-div" id="SelectedItemsDiv">
                    @for (int i = 0; i < Model.checkBoxList.Count; i++)
                    {
                        @Html.HiddenFor(model => Model.checkBoxList[i].Id)

                        @Html.CheckBoxFor(model => Model.checkBoxList[i].IsChecked, new { @class = "" })
                        @Html.DisplayFor(model => Model.checkBoxList[i].Name) <br />
                    }
                </div>
//its for dynamic client side creation any on-change based loading list
 
$.each(Items, function (i, iteam) {
 $("#SelectedItemsDiv").append('<input id="checkBoxList_' + i +
                                  '__Id" name="
checkBoxList[' + i + '].Id" type="hidden" value="' + iteam.Value + '"><input class="" id="checkBoxList_' + i +
                                  '__IsChecked" name="
checkBoxList[' + i + '].IsChecked" type="checkbox" value="true"><input name="checkBoxList[' + i + '].IsChecked" type="hidden" value="false">' + iteam.Text + ' <br>')

CONTROLLER POST ACTION GET DATA
 public async Task<ActionResult> Create(ViewModelClass model)
        {

int[] selectedIteams = model.checkBoxList.Where(x => x.IsChecked == true).Select(x => x.Id).ToArray();
                    if(selteams.Length>0 && selteams!=null)
                    {

                             //get only checked items id
                     } 
return RedirectToAction("Index");//redirect to list

 




Tuesday, 6 September 2016

Set asterisk(*) for required field using css

CSS
.required:after
{
color:red; content:" *";
}
Example:
<label class="required" >Name</label>
It will show
Name *

Word break using CSS

.class-wordbreak {
    word-break: break-all;
    word-wrap: break-word;
}

Wednesday, 10 August 2016

Time Zone based UTC and Local Date Time Conversion (C#,MVC,Asp.Net,.Net)

Get offset from browser(client side front end):
 Reason:
              Client side because we use .Net system DateTime Offset means it will take file hosted server DateTime so take it client side and store it in cookies.
Put it in Layout page and Login page
Java Script:
<script>
        var d = new Date();//for getting time zone
        var n = d.getTimezoneOffset();//it will returns difference in minutes
        var TimezoneOffset = "TimezoneOffset=" + n;
        document.cookie = TimezoneOffset;
</script>


Server side common function C#:

// LocalToUtc for store date time in UTC

 public static DateTime LocalToUtc(DateTime LocalDT, double offset)
        {

            //if offset>0 then subtract offset else add offset
            //offset=UTC-Local Date Time
            if (offset < 0)//local date time > UTC
            {
                return LocalDT.AddMinutes(offset);//utc=local time - offset
                //example if LocalDT=6.00 and offset=-330(5.30) then UTC=0.30
            }
            else if (offset > 0)//local date time < UTC
            {
                return LocalDT.AddMinutes(offset * (-1));//
            }
            else { return LocalDT; }

        }

// UtcToLocal for Display date time in Local

public static DateTime UtcToLocal(DateTime UTCDT, double offset)
        {
            //return DT.AddMinutes(offset);
            //offset=UTC-Local Date Time
            if (offset < 0)//local date time > UTC
            {
                //DateTime x = UTCDT.AddMinutes(offset * -1);
                return UTCDT.AddMinutes(offset * (-1));//local time=utc + offset
                //example if LocalDT=6.00 and offset=-330(5.30) then UTC=0.30
            }
            else if (offset > 0)//local date time < UTC
            {
                //DateTime x = UTCDT.AddMinutes(offset);
                return UTCDT.AddMinutes(offset);
            }
            else { return UTCDT; }
        }
Controller or server side  C#:

public class TimeZoneCoversinController : Controller

    {
         //from cookies get TimezoneOffset
          double TimezoneOffset = double.Parse(Request.Cookies["TimezoneOffset"].Value.ToString());
           //user date time
              DateTime dt=DateTime.Now;   //Local time
              DateTime Utcdt=LocalToUtc(DateTime.Now,TimezoneOffset );//To UTC
              DateTime Localdt=UtcToLocal(Utcdt,TimezoneOffset );//To Local
           
     }






Sunday, 31 July 2016

Validate Address or Place through google API

<html>
<head>
 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&key=Your API Key"></script>
    <script type="text/javascript">
        google.maps.event.addDomListener(window, 'load', function () {
            var places = new google.maps.places.Autocomplete(document.getElementById('Address'));
            getLatLong(places);
           
        });

        function placeLastOfFocus()
        {
            // alert(1);
           
           
            // alert(places);
            //document.getElementById('Address').value
            //!a.trim()
            if (!document.getElementById('Address').value.trim()) {
               
                $("#Address1").val('');
                $("#latitude").val('');
                $("#longitude").val('');
                return;
            }
            //doGeocode();
            var places = new google.maps.places.Autocomplete(document.getElementById('Address'));
            getLatLong(places);
        }
        function doGeocode() {
            var addr = document.getElementById("Address");
            // Get geocoder instance
            var geocoder = new google.maps.Geocoder();

            // Geocode the address
            geocoder.geocode({ 'address': addr.value }, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK && results.length > 0) {

                    // set it ot he correct, formatted address if it's vadlid
                    addr.value = results[0].formatted_address;;
                    alert("valid");
                    // show an error if it's not
                } else alert("Invalid address");
            });
        };
        function getLatLong(places)
        {
            google.maps.event.addListener(places, 'place_changed', function () {
                $("#Address").val('');
                $("#latitude").val('');
                $("#longitude").val('');
                //alert(1);
                var place = places.getPlace();
                var address = place.formatted_address;
                var latitude = place.geometry.location.lat();
                var longitude = place.geometry.location.lng();
                //var city = place.geometry.location.city();
                //alert(address);
                //for testing purpose alert
                var mesg = "Address: " + address;
                mesg += "\nLatitude: " + latitude;
                mesg += "\nLongitude: " + longitude;
                //alert(mesg);
                $("#Address1").val(address);
                $("#latitude").val(latitude);
                $("#longitude").val(longitude);
            });
        }
    </script>
</head>
<body>                                          
 <textarea name="Address" id="Address" autocomplete="on" class="col-lg-offset-5" ></textarea>
    <input type="text" name="latitude" id="latitude" autocomplete="on" />
    <input type="text" name="longitude" id="longitude" autocomplete="on" />
</body>
</html>

Wednesday, 27 July 2016

MVC Form OnSubmit Client side function calling

html-beginform-using-onsubmit-to-validate

@using (Html.BeginForm("Save", "ReadingsEntry", FormMethod.Post, 
new { enctype = "multipart/form-data", onsubmit = "validateForm(event)" }))

//add javascript function like validateForm(event){//do your code}
<script>
function validateForm(event)
{
//do your code
}
</script>

Thursday, 21 July 2016

Drop Down List Default Selected Value in MVC C#.

Controller:
DataTable dt = new DataTable();
            dt.Columns.Add("Value", typeof(int));
            dt.Columns.Add("Text", typeof(string));
            dt.Rows.Add(1, "Arul");
            dt.Rows.Add(2, "Kumar");
            dt.Rows.Add(3, "Arulkumar");
           

            ViewBag.DDL = new SelectList(dt.AsDataView(), "Value", "Text",2);
//where 2-for selected value Kumar
View
//DDL is viewbag name
@Html.DropDownList("DDL ", null, htmlAttributes: new { @class = "form-control" })

Monday, 18 July 2016

Place search using Google API

Live Example Here
<!--header-->
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>

<script type="text/javascript">
google.maps.event.addDomListener(window, 'load', function () {
var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'));
google.maps.event.addListener(places, 'place_changed', function () {
var place = places.getPlace();
var address = place.formatted_address;
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
//var city = place.geometry.location.city();
//alert(address);
//for testing purpose alert
var mesg = "Address: " + address;
mesg += "\nLatitude: " + latitude;
mesg += "\nLongitude: " + longitude;
// alert(mesg);
//$("#address").val(address);
//$("#latitude").val(latitude);
//$("#longitude").val(longitude);
});
});
</script>
</head>

<body>
<textarea id="txtPlaces" name="txtPlaces" placeholder="Enter place to search" class="f-location" required></textarea>
</body>
</html> 

Monday, 11 July 2016

Image upload through ajax

// create model for controller
var model = new FormData();
model.append('Name', $.trim($contestForm.find('[name="nombre"]').val()) + ' ' + $.trim($contestForm.find('[name="apellido"]').val()));
model.append('Email', $.trim($contestForm.find('[name="email"]').val().toLowerCase()));
model.append('City', $.trim($contestForm.find('[name="cuidad"]').val()));
model.append('Title', $.trim($contestForm.find('[name="title"]').val()));
model.append('Description', $.trim($contestForm.find('[name="description"]').val()));
model.append('CountryCode', 'co');
model.append('Image', $contestForm.find('[name="file-es"]')[0].files[0]);  // this has the file for sure

$.ajax({
    url: '/Umbraco/api/ControllerName/CreateContestEntry',
    type: 'POST',
    dataType: 'json',
    data: model,
    processData: false,
    contentType: false,// not json
    complete: function (data) {
        var mediaId = $.parseJSON(data.responseText); //?

    },
    error: function (response) {
        console.log(response.responseText);
    }
});

Shortcut key sample in javascript

Shortcut key sample
$(window).keydown(function(e) {
  switch (e.keyCode) {
    case 37: // left arrow key
    case 38: // up arrow key
      e.preventDefault(); // avoid browser scrolling due to pressed key
      // TODO: go to previous image
      return;
    case 39: // right arrow key
    case 40: // up arrow key
      e.preventDefault();
      // TODO: go to next image
      return;
  }
});

Sunday, 3 July 2016

Data Columns to combined string Without Loop in C#


string prd_str = string.Join(", ", DataTableDt.Rows.OfType<DataRow>().Select(r => r[3].ToString()));

Join Two DataTables Using LINQ in C#

var result = from dataRows1 in table1.AsEnumerable()
             join dataRows2 in table2.AsEnumerable()
             on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID") into lj
             from r in lj.DefaultIfEmpty()
             select dtResult.LoadDataRow(new object[]
             {
                dataRows1.Field<string>("ID"),
                dataRows1.Field<string>("name"),
                r == null ? 0 : r.Field<int>("stock")
              }, false);

Friday, 24 June 2016

Print option in web page

  <!--Include JQuery header file -->
 <!--prin script put it in end of the body -->
    <script type="text/javascript">
        $(document).ready()
        {
            function printData() {
                //alert(1);
                var divToPrint = document.getElementById("PrintelementID");
                newWin = window.open("");
                newWin.document.write(divToPrint.outerHTML);
                newWin.print();
                newWin.close();
            }
         //btnPrint button id
            $('#btnPrint').on('click', function () {
                               printData();
            })

        }
    </script>

Wednesday, 15 June 2016

Client Side common validation using Jquery

//class name based date
$(function () {
    $(".datepicker").datepicker({ dateFormat: "mm/dd/yyyy" });
    //$(".datepicker").datepicker({ dateFormat: "dd-mm-yy" });
    //dateFormat: 'dd-mm-yy'
});

//Common Messagebox
function commonMsgBox(msg) {
    try {
        alert(msg);
    }
    catch (exception) {
        return;
    }
    finally {
        return;
    }

}

Allow only numbers in input text
 <input type="text" onkeypress="allow_only_numbers(event);" />
function allow_only_numbers(e) {
    try {

        var kCode;
        if (e.keyCode) {
            kCode = e.keyCode;

        }
        else {
            kCode = e.charCode;
            if (kCode == 37 || kCode == 46 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 38) {
                e.preventDefault();
                return;
            }
        }
        var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 37, 39, 46, 35, 36, 9];

        if (!($.inArray(kCode, key_codes) >= 0)) {
            e.preventDefault();

        }

    }
    catch (ex) {

    }
}

Allow only float values in input text
 <input type="text" id="floattxt" onkeypress="allow_only_numbers(event,'floattxt');" />
function allow_only_Float(e, cntrl) {
    try {
        var tChkDecimal = $("#" + cntrl).val();

        var kCode;
        if (e.keyCode) {
            kCode = e.keyCode;
        }
        else {
            kCode = e.charCode;
            if (kCode == 37 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 38) {
                e.preventDefault();
                return;
            }
        }
        if (kCode == 46) { if ((tChkDecimal.split(".").length) > 1) { e.preventDefault(); return; } }
        var key_codes = [46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 37, 39, 46, 35, 36, 9];
        if (!($.inArray(kCode, key_codes) >= 0)) {
            e.preventDefault();
            return;
        }

    }
    catch (ex) {

    }
}



Allow only float TAX% values <=99.9 in input text
 <input type="text" id="floatTaxttxt" onkeypress="allow_only_Float_tax(event,'floatTaxttxt');" />
function allow_only_Float_tax(e, cntrl) {
    try {
        var tChkDecimal = $("#" + cntrl).val();

        var kCode;
        if (e.keyCode) {
            kCode = e.keyCode;
        }
        else {
            kCode = e.charCode;
            if (kCode == 37 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 38) {
                e.preventDefault();
                return;
            }
        }
        if (tChkDecimal != null && tChkDecimal != "") {
            if (parseFloat(tChkDecimal) > 99 && kCode != 8 && kCode != 46 && kCode != 37 && kCode != 39)
            { e.preventDefault(); $("#" + cntrl).val(tChkDecimal.substring(0, tChkDecimal.length - 1)); return; }
        }
        if (kCode == 46) { if ((tChkDecimal.split(".").length) > 1) { e.preventDefault(); return; } }
        var key_codes = [46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 8, 37, 39, 46, 35, 36, 9];
        if (!($.inArray(kCode, key_codes) >= 0)) {
            e.preventDefault();
            return;
        }

    }
    catch (ex) {

    }
}

Allow only Alphabets in input text
 <input type="text" id="txtText" onkeypress="allow_only_Float_tax(event,'txtText');" />
function allow_only_alphabets_name(e) {
    try {
        var kCode;
        if (e.keyCode) {
            kCode = e.keyCode;

        }
        else {
            kCode = e.charCode;
            if (kCode == 37 || kCode == 46 || kCode == 39 || kCode == 35 || kCode == 36 || kCode == 38) {
                e.preventDefault();
                return;
            }
        }

        var key_codes = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 32, 46, 8, 9, 37, 39, 40, 46, 35, 36];
        if (!($.inArray(kCode, key_codes) >= 0)) {
            e.preventDefault();
        }

    }
    catch (ex) {
        //commonMsgBox(ex.toString);
    }
}


//regular exp value based validate Mobile numbers
function validateNumbers(numbers) {
    try{
        var sum = 0;    
     
        var no = parseInt(numbers);
        while (no > 0) {
            sum = sum + no % 10;
            no = Math.floor(no / 10);
        }
        //  alert("Sum of digits  "+sum);
        if (sum == 0) {
            return false;
        }
        var filter = /^[0-9]+$/;
        return filter.test(numbers);
    }
    catch (ex)
    {
        alert(ex);
    }
}

//regular exp value based validate Email
function validateEmail(email) {
    var re = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

    return re.test(email);
}

//on change image validate
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        //reader.onload = function (e) {
        //    $('#emp_img').attr('src', e.target.result);
        //    $('#EMAddImag').attr('src', e.target.result);
        //}

        reader.readAsDataURL(input.files[0]);
    }
}

$(".imagefile").change(function () {
    readURL(this);
    var val = $(this).val();
  
    switch (val.substring(val.lastIndexOf('.') + 1).toLowerCase()) {
        case 'gif': case 'jpg': case 'png': case 'jpeg': case 'GIF' : case 'JPG': case 'PNG': case 'JPEG':
            break;
        default:
            $(this).val('');
            // error message here
            commonMsgBox("Upload only image format (jpg,jpeg,gif,png)");
            break;
    }
    //alert(this.files[0].size/1000);
    var imagesize = parseFloat(this.files[0].size) / 1000;//kb to mb
    if(imagesize>2000)
    {
        $(this).val('');
        commonMsgBox("Image Size Too Large You Can Upload Image Size Less Than 2MB only!")
    }
});

//Date validate
function checkdate(input) {
    alert(input);
    var validformat = /^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
    var returnval = false
    if (!validformat.test(input.value))
        alert("Invalid Date Format. Please correct and submit again.")
    else { //Detailed check for valid date ranges
        var monthfield = input.value.split("/")[0]
        var dayfield = input.value.split("/")[1]
        var yearfield = input.value.split("/")[2]
        var dayobj = new Date(yearfield, monthfield - 1, dayfield)
        if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
            alert("Invalid Day, Month, or Year range detected. Please correct and submit again.")
        else
            returnval = true
    }
    if (returnval == false) input.select()
    return returnval
}