JavaScript

UK Postcode Validation

Regular expression for JavaScript

var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/;

var result = regPostcode.test(SearchTerm);

if (!result) {
alert(“Please enter valid postcode”);
return false;
}

Regular expression for C#

string regPostcode = “([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9][a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}”;

System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex(regPostcode);

if(!regx.IsMatch(address0.PostalCode))
{
results.Add(new ValidationResult(String.Format(“Please enter valid postcode for {0}.”, addressRank)));
}

You can check the regular expression at http://www.regexplanet.com/

Postal code format and sample postcodes are as below.

Format Example
A9 9AA S1 1AA
A99 9AA M60 1NW
AA9 9AA CR2 6XH
AA99 9AA DN55 1PT
A9A 9AA W1A 1HQ
AA9A 9AA EC1M 1BB

Add Comma into number using javascript


<script>

addCommas = function(input){
  // If the regex doesn't match, `replace` returns the string unmodified
  return (input.toString()).replace(
    // Each parentheses group (or 'capture') in this regex becomes an argument 
    // to the function; in this case, every argument after 'match'
    /^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {

      // Less obtrusive than adding 'reverse' method on all strings
      var reverseString = function(string) { return string.split('').reverse().join(''); };

      // Insert commas every three characters from the right
      var insertCommas  = function(string) { 

        // Reverse, because it's easier to do things from the left
        var reversed           = reverseString(string);

        // Add commas every three characters
        var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');

        // Reverse again (back to normal)
        return reverseString(reversedWithCommas);
      };

      // If there was no decimal, the last capture grabs the final digit, so
      // we have to put it back together with the 'before' substring
      return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
    }
  );
};

</script>

How to call this function?

$.fn.addCommas = function() {
$(this).each(function(){
$(this).text(addCommas($(this).text()));
});
};

how to read resource file in jquery or javascript or js file

As generally we do in asp.net project, I have created a global resource file for storing common error messages, info messages, labels etc in my first MVC4 project. I used ready-made validation.js for giving validation. I have face the problem how to get the resource file’s object value in .js file. From come out this problem I have find a way. I had create a controller ‘ResoruceScript’. And added below code in ActionResult method.

        public ActionResult Index()
        {
            Response.Clear();            
            Response.ContentType = "text/javascript";
            
            return View();
        }

Then create a view for “Index” Action. And remove the html content, all tags which are added by default when we create a new view. And below code.


        @using System.Collections
@using System.Globalization
@using System.Resources
@using Pharma
@{
    Layout = null;
    // Get a set of resources appropriate to the culture defined by the browser
    ResourceSet resourceSet = @Resources.PharmaCore.ResourceManager.GetResourceSet
        (CultureInfo.CurrentUICulture, true, true);
}

// Define the empty object in javascript
var Resources = {};
@foreach (DictionaryEntry res in resourceSet)
{
    // Create a property on the javascript object for each text resource
    @:Resources.@res.Key = "@Html.Raw(
        HttpUtility.JavaScriptStringEncode(res.Value.ToString()))";
}

Here, PharmaCore is my resource file name. Above code create the array of resource file’s objects. Add this view as javascript file in head tag or anywhere in the page but before the use of resource value. I have added in head tag of page.

 <script src="~/ResourceScript"&gtl</script>

Now, you are able to get the resource file’s object value as ‘Resources.rfv_Common_Msg’ in .js file.

Telerik RadList Box Checkbox Items check all or uncheck all

Aspx page: I bound the lstLocations dynamically. So it look like as below.

Capture

<telerik:RadListBox ID=”lstLocations” runat=”server” CheckBoxes=”true” Width=”520px”
Height=”130px”>
</telerik:RadListBox>

// Select All checkbox buttons
<asp:CheckBox CssClass=”CBFull” ID=”chkSelectAll” runat=”server” Text=”Select All”
onclick=”javascript:return ToggleAllLocations(this);” />
// Add below function in javascript function



function ToggleAllLocations(checkBox) {
             //ctl00_ContentPlaceHolder1_RadDockLocFilter_C_lstLocations is a client id of radlistbox                   
            var listbox = $find("ctl00_ContentPlaceHolder1_RadDockLocFilter_C_lstLocations");

            var j = listbox.get_checkedItems().length;

            if (!document.getElementById(checkBox.id).checked) {
                for (var i = 0; i < j; i++) {
                    listbox.get_checkedItems()[0].uncheck();
                }
            }
            else {
                for (var i = 0; i < listbox.get_items().get_count(); i++) {
                    var item = listbox.getItem(i);
                    listbox.trackChanges();

                    item.set_checked(true);

                    listbox.commitChanges();

                }                                           
            }
            return true;
        }


How to read RSS feed using Jquery

Click here download latest plugin

Getting Started
First include the jQuery and zRSSFeed libraries.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="jquery.zrssfeed.min.js" type="text/javascript"></script>

Add a DIV tag where you wish the feed to display and give it an ID. There is no need to specify a class, this will be added.

<div id="test"></div>

Now add the script to call the zRSSFeed plugin with the RSS URL and any options. Our example gets 5 feeds from the Reuters site.

<script type="text/javascript">
$(document).ready(function () {
  $('#test').rssfeed('http://feeds.reuters.com/reuters/oddlyEnoughNews', {
    limit: 5
  });
});
</script>

More option you can get by click here

Send free SMS API

http://ubaid.tk/api-usage/

Required Params : uid, pwd, phone, msg.

uid : your userid for the required sms provider
pwd : your password for the required sms provider
provider : way2sms(default), fullonsms, smsindia, whozzat, smsinside, site2sms. if you do not specify any provider, way2sms will be used by default.
phone : phone number whom you want to send sms. seperate multiple phone numbers with a comma (,)
msg : your sms message, unlimited chars. will be sent as multiple msgs if crosses the message length for any provider

Optional Parameters
codes : 1. Send this if you require a user friendly msg from the server. for example, if codes=1 is not provided the server will return the result as an integer.
1 – SMS sent
-1 – Server Error
-2 – Invalid Username
-3 – Invalid message text
-4 – Login Failed
-5 – IP Blocked

JavaScript to redirect to https


function RedirNonHttps() {
    if (location.href.indexOf("https://") == -1) {
        location.href = location.href.replace("http://", "https://");
    }
}

Then, simply call the RedirNonHttps function on page load :

onload="RedirNonHttps();"

jQuery Beginners Guide

Adding jQuery to your Page
jQuery is a client script library and so you have to add a script reference to your page. You can download the latest version of jQuery from the jQuery site at www.jQuery.com.

Here are many ways that you can include jQuery into your page:

1. Reference a local copy via tag in the page
2. Reference a local copy with ScriptManager
3. Embed script from Resource using the ClientScript object
4. Reference a remote copy from jQuery.com or Google Ajax API

Getting started with Selectors
You can select a single element:
$(“#gdEntries”).css(“border”, “solid 1px navy”);

Or select by class (.):
$(“.gridalternate”).css(“background”, “lightsteelblue “);

or from a couple of classes (, like in CSS separates multiple selectors):
$(“.gridrow,.gridalternate”).attr(“tag”, “row”);

You can also select elements (plain element) and apply filters to the elements. The following selects all buttons in a document and attaches a click handler:

$(“input:button “).click(function(event) { alert(“clicked”); });

A more complex example might select all rows in a table:
$(“#gdEntries>tbody>tr”).css(“border”, “solid 1px red”);

Refer this link: http://www.west-wind.com/presentations/jquery/