Friday, February 28, 2014

JavaScript Regular Expression Basics

Regular Expression is a pattern that matched a given input string. The pattern can be formed by using meta characters.

Meta characters

char meaning

^   => beginning of string
$   => end of string
.  => any character except newline
*  =>match 0 or more times
+ =>match 1 or more times
? =>match 0 or 1 times; or: shortest match
| =>alternative
( ) =>grouping; “storing”
[ ] =>set of characters
{ } =>repetition modifier

Repetition

a* =>zero or more a’s
a+ =>one or more a’s
a? =>zero or one a’s (i.e., optional a)
a{m} =>exactly m a’s
a{m,} =>at least m a’s
a{m,n} =>at least m but at most n a’s

Syntax in JavaScript
var patt=new RegExp(pattern,modifiers);
or

var patt=/pattern/modifiers;

Modifiers
1) The i modifier is used to perform case-insensitive matching.
2) The g modifier is used to perform a global match 

Pattern

  • Username [Min 8 Chars and alpha numeric characters)

    /^[a-z0-9]{8,}/i

  • Email ID

    /^[a-z0-9._-]+@[a-z]+.[a-z.]{2,5}$/i

  • Date of Birth

    /^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$/i
  • Mobile Number

    /^([+0-9]{1,3})?([0-9]{10,11})$/i

  • Web Site URL

    /^[http://]+[www]?.[0-9a-z_.]+.[a-z.]{2,5}$/i

  • Pincode

    /^[0-9]{6}$/i 

SAMPLE CODE

<!DOCTYPE html>
<html>
    <head>
        <title>Test Script</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <div>
            <form id="myform" method="post">
                Enter the Username
                <input type="text" id="uname" /> <br />
                <input type="submit" value="Validate"/>
            </form>
            <script>
 
                document.getElementById("myform").onsubmit =function()
                {
                 var pattern = /^[a-z0-9_]{8,25}$/i;
                 var text = document.getElementById("uname");
                 if(!pattern.test(text.value))
                   {
                     alert("Enter a valid Username");
                     text.focus();
                    }
                  else
                   {
                     alert("Thank You");
                   }
                };  
            </script>
        </div>
    </body>
</html>



With Regards,
Animesh Nanda
Sr.Software Engineer | Photon Infotech
Bengaluru | Karnataka | INDIA.

Sunday, February 23, 2014

HTML 5 Geo-location API

The Geo-location API lets you share your location with trusted web sites. The latitude and longitude are available to JavaScript on the page, which in turn can send it back to the remote web server and do fancy location-aware things like finding local businesses or showing your location on a map.
As you can see from the following table, the geolocation API is supported by most browsers on the desktop and mobile devices. 

GEO-LOCATION API SUPPORT

  • IE 9.0+
  • Firefox 3.5+
  • Safari 5.0+
  • CHROME 5.0+
  • OPERA 10.6+
  • IPHONE 3.0+
  • ANDROID 2.0+
CODE

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your position:</p>
<button onclick="getLocation()">Show in MAP</button>
<div id="mapholder"></div>
<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }

function showPosition(position)
  {
  var latlon=position.coords.latitude+","+position.coords.longitude;

  var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
  +latlon+"&zoom=14&size=400x300&sensor=false";
  document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
  }

function showError(error)
  {
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }
</script>
</body>

</html>

Regards,

Animesh Nanda

Sr. Software Engineer,
Photon Infotech Pvt. Ltd.

Sunday, February 16, 2014

A fix for window.location.origin in Internet Explorer

Internet Explorer does not have access to window.location.origin, which is a bummer because it is a pretty handy variable to have, but we can make it work with a fairly straight forward check because we access .origin;

if (!window.location.origin) {
 window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}

This should now have .origin set to what you would expect.


Regards,

Animesh Nanda

Sr. Software Engineer,
Photon Infotech Pvt. Ltd.