JavaScript for restricting users from entering unwanted characters in a textbox/ text field.!
One of the easiest way of restricting a user from entering unwanted characters in a text field can be accomplished by using JavaScript functions as below:
<script type="text/javascript" language="javascript">
function keyRestrict(e, validchars)
{
var key='', keychar='';
key = getKeyCode(e);
if (key == null) return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
validchars = validchars.toLowerCase();
if (validchars.indexOf(keychar) != -1)
return true;
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
return false;
}
function getKeyCode(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
</script>
After placing the above script in your head section of the web page all you need to do is call the function on the keypress event of a textbox/text field and pass in all the characters that you want to be allowed as follows:
< type="text" name="zip" id="zip" style="width:100px;" maxlength="7" onkeypress="return keyRestrict(event,'1234567890. ')" />>
Note: Please ensure that you conduct server side validations for user input, as JavaScript can be easily disabled in any browser and the above restrictions can be bypassed.
ASP.NET MVC, Javscript, JQuery, Angular JS, HTML 5, CSS3
Web Services, Web Api, SQL Server, C#.NET, Azure
Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts
06 January 2009
26 December 2008
Javascript RegExp Function
JavaScript provides a very useful function for client side user input validation. This function uses regular expressions for validation against the input.
If you are a PHP developer then you must have knowledge of this feature, whereas for ASP.NET 2.0 we already have the regular expression validator control which also uses similar regular expressions.
A simple example of the RegExp is as follows:
<script type="text/javascript" langusge="javascript">
function validate_phone(obj)
{
//for US phone number format: (xxx) xxx-xxxx
var RegExp=/\(\d{3}\)\ \d{3}-\d{4}/;
if(RegExp.test(obj.value))
{
return true;
}
else
{
obj.select();
obj.focus();
return false;
}
}
</script>
Note: Passing a correct regular expression is very important. You can find various regular expressions according to your need by Googling around. Also note that the regular expression must be inside the / / i.e var RegExp=/ /;
If you are a PHP developer then you must have knowledge of this feature, whereas for ASP.NET 2.0 we already have the regular expression validator control which also uses similar regular expressions.
A simple example of the RegExp is as follows:
<script type="text/javascript" langusge="javascript">
function validate_phone(obj)
{
//for US phone number format: (xxx) xxx-xxxx
var RegExp=/\(\d{3}\)\ \d{3}-\d{4}/;
if(RegExp.test(obj.value))
{
return true;
}
else
{
obj.select();
obj.focus();
return false;
}
}
</script>
Note: Passing a correct regular expression is very important. You can find various regular expressions according to your need by Googling around. Also note that the regular expression must be inside the / / i.e var RegExp=/ /;
24 December 2008
Regular Expression for File Upload Validation
This is a Regular Expression for validating the file upload HTML/ASP.NET control on the client side using JavaScript!
" ^.+\.(([jJ][pP][eE]?[gG]) | ([gG][iI][fF]) | ([bB][mM][pP]) | ([pP][nN][gG]) |([wW][mM][fF]))$ "
As you can see you can specify any file format between the | | fields which stand for OR.
You can use this function in ASP.NET 2.0 with the Regular Expression Validator or can use the JavaScript RegExp function for PHP.
Note: Its always a good idea to validate the user input on the server side!!
" ^.+\.(([jJ][pP][eE]?[gG]) | ([gG][iI][fF]) | ([bB][mM][pP]) | ([pP][nN][gG]) |([wW][mM][fF]))$ "
As you can see you can specify any file format between the | | fields which stand for OR.
You can use this function in ASP.NET 2.0 with the Regular Expression Validator or can use the JavaScript RegExp function for PHP.
Note: Its always a good idea to validate the user input on the server side!!
22 December 2008
Using Session variables in Javascript
One of the common problems Web Developers face is interaction between client side and server side scripts. With the advent of AJAX it has become very simple.
But there are situations were we need to change the JavaScript variables dynamically without changing the rest of the script. For example some flash elements require JavaScript variables for their functionality like keeping track of the tabs.
This can be achieved very easily through the use of session variable as follows:
<script type="text/javascript" language="javascript">
function myFunction()
{
var var1=21;
var var2=<%=Convert.ToString(Session["myVariable"])%>
------
------
------
}
</script>
All you need to do is assign the session variable with the value you want on the page load in code behind.
I was quiet curious and also tried the vice verse i.e assigning a Session Variable in JavaScript. But it doesn't work !!!! Have to use alternate methods. If any one knows a way of doing so..Please Comment
But there are situations were we need to change the JavaScript variables dynamically without changing the rest of the script. For example some flash elements require JavaScript variables for their functionality like keeping track of the tabs.
This can be achieved very easily through the use of session variable as follows:
<script type="text/javascript" language="javascript">
function myFunction()
{
var var1=21;
var var2=<%=Convert.ToString(Session["myVariable"])%>
------
------
------
}
</script>
All you need to do is assign the session variable with the value you want on the page load in code behind.
I was quiet curious and also tried the vice verse i.e assigning a Session Variable in JavaScript. But it doesn't work !!!! Have to use alternate methods. If any one knows a way of doing so..Please Comment
25 November 2008
Five JavaScript Best Practices
JavaScript is an extremely powerful and flexible scripting language. Unfortunately flexible, for many people, means fallible. I am going to highlight 5 best practices that you can use in any JavaScript project.
>>.First and foremost, keep your code simple, clean and well documented. This is by no means unique to JavaScript but many people seem to think it is the exception to the rule. Your code should naturally comment itself but it is also important to at least introduce every function. I recommend two versions, a fully documented and formatted version and then a compressed version that you use in production. There are a number of free online utilities that can strip out comments and pack your script. There is no need to push out the extra size required for the documentation and formatting.
>>.Second, keep your JavaScript in an external file. The only exception to this rule is if you have some very lightweight script specific to a single page or are setting up variables that cannot be done in the external JS. An external file results in greater scalability, maintainability and degradability. The correct way to reference an external JS file is as follows:
<script type="text/javascript" src="script.js"></script>
>>.Third, separate your JavaScript from the presentation layer. We have all heard of unobtrusive JavaScript but we still see inline script all the time. Instead of cluttering your font-end code with dozens of event handlers add them dynamically. There are exceptions to this rule so please use common sense and separate the layers when it makes sense. An example of adding an onclick event handler from JavaScript:
var div = document.getElementById('div');
div.onclick = new Function("processClick(this)");
>>.Fourth, properly define and scope variables. Many of the scripts I download hoping to use in a project I immediately throw out. The reason being that the programmer did not take the time to properly define and scope variables. Always reference the first instance of a variable by using var. Otherwise the only way someone can know if that is the first reference to that variable is by starting at the top and reading all the way down. It is also important to scope variables correctly. Don’t scope a variable on the global level unless you need it there. I also recommend differentiation of global and local variables though some kind of visual identifier such is all caps on global variables or some easily identifiable character.
>>.Fifth, don’t assume JavaScript support in the first place. Depending on your audience you may choose to disregard this suggestion but for mainstream websites I highly suggest coding with the minority in mind (an estimated 5-10% of web users do not have JavaScript enabled) and degrade your scripts gracefully. JavaScript should be considered as an added feature and not a dependency. An examples of this would be links, the most fundamental element of a web page.
<a href="javascript:processClick()">link</a>
<a href="#" onclick="javascript:processClick()">link</a>
If the user clicks the either of the links above with JavaScript disabled nothing will happen. However, with the code below they could still navigate.
<a href="link.html" onclick="processClick(); return false;">link</a>
>>.First and foremost, keep your code simple, clean and well documented. This is by no means unique to JavaScript but many people seem to think it is the exception to the rule. Your code should naturally comment itself but it is also important to at least introduce every function. I recommend two versions, a fully documented and formatted version and then a compressed version that you use in production. There are a number of free online utilities that can strip out comments and pack your script. There is no need to push out the extra size required for the documentation and formatting.
>>.Second, keep your JavaScript in an external file. The only exception to this rule is if you have some very lightweight script specific to a single page or are setting up variables that cannot be done in the external JS. An external file results in greater scalability, maintainability and degradability. The correct way to reference an external JS file is as follows:
<script type="text/javascript" src="script.js"></script>
>>.Third, separate your JavaScript from the presentation layer. We have all heard of unobtrusive JavaScript but we still see inline script all the time. Instead of cluttering your font-end code with dozens of event handlers add them dynamically. There are exceptions to this rule so please use common sense and separate the layers when it makes sense. An example of adding an onclick event handler from JavaScript:
var div = document.getElementById('div');
div.onclick = new Function("processClick(this)");
>>.Fourth, properly define and scope variables. Many of the scripts I download hoping to use in a project I immediately throw out. The reason being that the programmer did not take the time to properly define and scope variables. Always reference the first instance of a variable by using var. Otherwise the only way someone can know if that is the first reference to that variable is by starting at the top and reading all the way down. It is also important to scope variables correctly. Don’t scope a variable on the global level unless you need it there. I also recommend differentiation of global and local variables though some kind of visual identifier such is all caps on global variables or some easily identifiable character.
>>.Fifth, don’t assume JavaScript support in the first place. Depending on your audience you may choose to disregard this suggestion but for mainstream websites I highly suggest coding with the minority in mind (an estimated 5-10% of web users do not have JavaScript enabled) and degrade your scripts gracefully. JavaScript should be considered as an added feature and not a dependency. An examples of this would be links, the most fundamental element of a web page.
<a href="javascript:processClick()">link</a>
<a href="#" onclick="javascript:processClick()">link</a>
If the user clicks the either of the links above with JavaScript disabled nothing will happen. However, with the code below they could still navigate.
<a href="link.html" onclick="processClick(); return false;">link</a>
24 November 2008
jQuery
jQuery is a lightweight open source java-script library (only 15kb in size) that in a relatively short span of time has become one of the most popular libraries on the web.
A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code. jQuery supports this via a nice "selector" API that allows developers to query for HTML elements, and then apply "commands" to them. One of the characteristics of jQuery commands is that they can be "chained"
together - so that the result of one command can feed into another. jQuery also includes a built-in set of animation APIs that can be used as commands. The combination allows you to do some really cool things with only a few keystrokes.
For example, the below java-script uses jQuery to find all <div> elements within a page that have a CSS class of "product", and then animate them to slowly disappear:
$("div.product").slideUp('slow').addClass("removed");
As another example, the java-script below uses jQuery to find a specific <table> on the page with an id of "datagrid1", then retrieves every other <tr> row within the datagrid, and sets those <tr> elements to have a CSS class of "even" - which could be used to alternate the background color of each row:
$("#datagrid1 tr:nth-child(even)").addClass("even");
[Note: both of these samples were adapted from code snippets in the excellent jQuery in Action book]
Providing the ability to perform selection and animation operations like above is something that a lot of developers have been begging for years. Such simplicity has never been offered before by any other development environment or library.
As a result even Microsoft has accepted this technology and they have already began shipping their Visual Studio 2008 package with jQuery preinstalled and with full support for it including intellisense. According to Scott Gu (Microsoft Developer, Blogger) - Microsoft is even working on adding new features and bug fixes to the jQuery Library.
A big part of the appeal of jQuery is that it allows you to elegantly (and efficiently) find and manipulate HTML elements with minimum lines of code. jQuery supports this via a nice "selector" API that allows developers to query for HTML elements, and then apply "commands" to them. One of the characteristics of jQuery commands is that they can be "chained"
together - so that the result of one command can feed into another. jQuery also includes a built-in set of animation APIs that can be used as commands. The combination allows you to do some really cool things with only a few keystrokes.
For example, the below java-script uses jQuery to find all <div> elements within a page that have a CSS class of "product", and then animate them to slowly disappear:
$("div.product").slideUp('slow').addClass("removed");
As another example, the java-script below uses jQuery to find a specific <table> on the page with an id of "datagrid1", then retrieves every other <tr> row within the datagrid, and sets those <tr> elements to have a CSS class of "even" - which could be used to alternate the background color of each row:
$("#datagrid1 tr:nth-child(even)").addClass("even");
[Note: both of these samples were adapted from code snippets in the excellent jQuery in Action book]
Providing the ability to perform selection and animation operations like above is something that a lot of developers have been begging for years. Such simplicity has never been offered before by any other development environment or library.
As a result even Microsoft has accepted this technology and they have already began shipping their Visual Studio 2008 package with jQuery preinstalled and with full support for it including intellisense. According to Scott Gu (Microsoft Developer, Blogger) - Microsoft is even working on adding new features and bug fixes to the jQuery Library.
22 November 2008
How to Set MaxLength of a Multiline TextBox
Ever tried setting up the maxlength property of a ASP.NET Multiline TextBox and ended up finding out that its doesn't work at all!! HEre's a simple solution using Javascript..
You can use the below script to set up the maxlength of a Multiline TextBox or even a HTML TextArea Tag:
<script type="text/javascript" language="javascript">
function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}
</script>
Inside any textarea you wish to add a "maxlength" attribute to, simply do the following:
<textarea maxlength="40" onkeyup="return ismaxlength(this)" ></textarea>
or
<asp:TextBox ID="txt1" runat="server" maxlength="40" onkeyup="return ismaxlength(this)" />
The part in green is what you should add, with "40" obviously being the maximum number of characters accepted by this textarea.
Note: In ASP.NET setting up the maxlength might not work. Hence you should replace the textbox with a textarea and run it as a server control using runat="server"
You can use the below script to set up the maxlength of a Multiline TextBox or even a HTML TextArea Tag:
<script type="text/javascript" language="javascript">
function ismaxlength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}
</script>
Inside any textarea you wish to add a "maxlength" attribute to, simply do the following:
<textarea maxlength="40" onkeyup="return ismaxlength(this)" ></textarea>
or
<asp:TextBox ID="txt1" runat="server" maxlength="40" onkeyup="return ismaxlength(this)" />
The part in green is what you should add, with "40" obviously being the maximum number of characters accepted by this textarea.
Note: In ASP.NET setting up the maxlength might not work. Hence you should replace the textbox with a textarea and run it as a server control using runat="server"
21 November 2008
Hide/Show Div Elements Using JavaScript
JavaScript can be used to bring interactivity to you web pages by performing client side scripting. Using the style property of an HTML element, the element can be hidden or shown to the user based upon the required condition. For Example:
<script>
function setDiv(id)
{
if(document.getElementById(id).value==0)
{
document.getElementById('myDiv').style.display='none';
}
else
{
document.getElementById('myDiv').style.display='block';
}
}
</script>
This function can be called on any event of another HTML element as:
<select id="mySelect" name="mySelect" onchange="setDiv(this.id)">
<option>Select one</option>
<option value="0">Hide</option>
<option value="1">Show</option>
</select>
<div id="myDiv" name="myDiv" style="display:none;">
<span>Hi......!!!!!!! </span>
</div>
You can place any thing inside the myDiv element. Further more buy using some jQuery you can even add some animation effects.
<script>
function setDiv(id)
{
if(document.getElementById(id).value==0)
{
document.getElementById('myDiv').style.display='none';
}
else
{
document.getElementById('myDiv').style.display='block';
}
}
</script>
This function can be called on any event of another HTML element as:
<select id="mySelect" name="mySelect" onchange="setDiv(this.id)">
<option>Select one</option>
<option value="0">Hide</option>
<option value="1">Show</option>
</select>
<div id="myDiv" name="myDiv" style="display:none;">
<span>Hi......!!!!!!! </span>
</div>
You can place any thing inside the myDiv element. Further more buy using some jQuery you can even add some animation effects.
11 November 2008
Javascript function to open a popup
This is a very important and handy javascript to open a popup window, useful in showing small bits of information to user without taking them to different page.
<script> function popup(url) { newwindow=window.open(url,'popup_name','height=500,width=400,left=100,top=100 resizable=yes,scrollbars=yes,toolbar=yes,status=yes'); if(window.focus){newwindow.focus();} } </script>
This function can be called on any event like mouse click by passing the url of the page to be opened in a popup.
Please Note: Firefox does not allow the popup window to be non resizable, hence this feature can not be seen in Mozilla Firefox.
<script> function popup(url) { newwindow=window.open(url,'popup_name','height=500,width=400,left=100,top=100 resizable=yes,scrollbars=yes,toolbar=yes,status=yes'); if(window.focus){newwindow.focus();} } </script>
This function can be called on any event like mouse click by passing the url of the page to be opened in a popup.
Please Note: Firefox does not allow the popup window to be non resizable, hence this feature can not be seen in Mozilla Firefox.
30 October 2008
Importance of Javascript
If you are a fresh web developer and just finished learning your very first server side scripting language aka ASP.NET, then you probably must be thinking why in the world should i learn another client side language aka Javascript. I mean you probably can get most of the things done by using the all mighty "ASP.NET" technology, can't you?
Well its time to get a reality check!! No web developer these days can survive without knowing javascript...take my word for it!!
Even i used to think the same way but soon realized that its not possible to stay without js. Take for example you want to show a alert message or get a confirmation from the user on the client side. You might think that using MessageBox.Show() would do the trick but it fails on many occasion as its a windows class library function. Instead you have to write something like this. in the head section of your html document inside the scripts tab("script").
var ans= confirm("Are you sure you want to do this?")
if(ans==true)
----
else
----
Well this is a good example for very first starters and you might find many other stuff accross the internet.
My point remains that you cannot ignore javascripts and start learning it immediately. A good webiste to get started is www.w3schools.com.
Well its time to get a reality check!! No web developer these days can survive without knowing javascript...take my word for it!!
Even i used to think the same way but soon realized that its not possible to stay without js. Take for example you want to show a alert message or get a confirmation from the user on the client side. You might think that using MessageBox.Show() would do the trick but it fails on many occasion as its a windows class library function. Instead you have to write something like this. in the head section of your html document inside the scripts tab("script").
var ans= confirm("Are you sure you want to do this?")
if(ans==true)
----
else
----
Well this is a good example for very first starters and you might find many other stuff accross the internet.
My point remains that you cannot ignore javascripts and start learning it immediately. A good webiste to get started is www.w3schools.com.
Subscribe to:
Posts (Atom)