Learning {{AngularJS}} with Examples–Part 1


Client side programming is becoming the one of the main parts of web applications. Now a days, We are seeing the explosion of JavaScript libraries. And the reason is that some JavaScript libraries got very popular and developers took them hand to hand because of its cool feature and almost negligible performance cost, Now in our projects,  count of JavaScript files (plugins and custom files) are increasing rapidly which is making it  unmanageable and unmaintainable. AngularJS provides best of the both the worlds and now a days, it is one of the most talked and used JavaScript framework in web applications. So I have thought to start a series of post on AngularJS. I’ll start from basics and gradually discuss all the features, keeping in mind the.NET Developers.  So let us start learning it. The first questions arises that

What is AngulalJS?

AngularJS is not just another JavaScript library but it provides a framework to write a proper architectured, maintainable and testable client side code. Some of the key points are

  • It follows MVC framework. If you don’t have Idea MVC framework, I’ll suggest you to get an Idea of MVC framework and then start learning AngularJS. You can refer below wiki page on MVC framework.
  • AngularJS is primarily aimed to develop SPAs (Single Page Applications), it means your single HTML document turns into application. But it is also used a lot in ASP.NET and other applications .
  • Allows you to write Unit and integration tests for JavaScript code. Testability is one of the main points, which was kept in mind while writing this framework so it has great support of it.
  • It provides it’s own and very rich list of attribute and properties for HTML controls which increases the usability of it exponentially.It is also called directives.
  • Supports two-way binding that means your data model and control’s data will be in sync.
  • Angular supports Dependency injection. Read more about dependency injection on wiki.
  • Angular library is also available on CDN so you just need to the url of the CDN and it available for use.

It is an Open Source

AngularJS is a open source library and developed and supported by Google. Being an open source, you can go through the code itself and customize it if required. There is lot of support from JavaScript community and even you can contribute to it.  Currently, more that 100 contributors have contributed and it is increasing day by day.

So let’s discuss the main components of AngularJS. These are

Controller – It is main component of AngularJS and contains the state and logic both. It acts as bridge between services and views.

Views/Directives –  Here we generate the UI. Directives extends the HTML element and enables us to generate the complex html easily. Controllers talks to view to both directions.

Services – It contains the core logic and state of the application. In it, we can communicate to server to get and post the data.

Now let’s see all the above components glued with each other.

image

Now you have got the basic explanation about the basics of AngularJS. So let’s jump to the coding. We need to learn two things mentioned below before writing the first application

1- {{expression}} – It is called expressions and JavaScript like code can be written inside. It should be used for mainly small operations in HTML page.

2- $scope – This is one of very important variable used in AngularJS. It provides and link between the data and views. It holds all the required data for the views and used with in the HTML template.

3- ng- – All the elements that are provided by angular starts from ng-. So if you see some attribute that ng- and angular library is also included in the page, then you can assume that this should be angular element only.

4- ng-app – This directive is used to bootstrap the application. Normally, it is put at in top level element like html or body tag. (That will be discussed in details in coming post).

Now lets write our first Hello World application with AngularJS. In this example, I’ll be using the basic construct of AngularJS. I have created Empty Project in Visual Studio and added an HTML page Home.html and written it as

NewExample

This is very simple page using AngularJS. I have encircled and numbered the specific part of the page that are relevant with AngularJS. Let’s discuss it one by one.

1- As discussed earlier that this attribute is required to bootstrap the AngularJS application so I have put it in body element. Here I have put it in body element so it AngularJS can be used inside the body tag. In the above application, I could have put it at h1 element as well because I am using AngularJS inside this tag only. The scope can be displayed pictorially as

image

2- Here I have included the angular library on the page using Google cdn.

3 – When ever we want to use the AngularJS , we need a controller. A JavaScript method HelloWorldCtrl is controller here. I appended Ctrl in the name as a naming convention

4- We already discussed what is $scope. This is a parameter in controller method and we can create dynamic properties and assign values to it, which can be later can be accessed in UI element. We can also create the controller in a new JS file that we’ll see in the coming posts.

image

5- Here we created a new property helloWorldMessage to $scope variable and assigns the message.

6- Now it’s time to use the controller. The controller can be defined over an element as ng-controller=<controller> given in the image as well.

7- Now we see the expression here. As we provided the controller in this element and we can access the property that we defined in the controller that we have used here.

Now it’s to run the application.

runningapp

We can see the message with date and time that we have provided.  Our page got rendered as per expectation. Now Let’s discuss the flow of the angular page. It can be depicted pictorially as

 

AngularFlow-New

 

So the above picture clearly illustrates that How does the flow of Angular page work at high level.

So In this post  we created a very simple page which has all the code on the same HTML page. In the next post, we’ll learn more concept and write a more detailed page and provide a better structure to the application.

Sample is attached with the application.

Hope you have enjoyed the post and will connect you again in next post.

Cheers,
Brij

Join me and Learn jQuery, Node.Js and Knockout.js

Hi All,

C# Corner Delhi chapter is hosting next event  on 23rd November at Noida and Become Better JS developer in a day. This time we are discussing various hot Client side libraries jQuery, Node.js and Knockout.js. After all the session, there will be Test which results will be online. This will be a full day event with full hands on exercises etc.

Date and Timing – 23rd November 2013, 10:30 PM to 6:00 PM

Is there any fee – No. It is Absolutely free

Venue -

MCN Solutions Pvt. Ltd.
H-217, Second Floor,
Sector-63, Noida
Landmark: Behind Indian-Oil Petrol Pump
Contact No: +91-9810371053

The agenda of the day will be :

agenda

For more details and registration Click Here

Join and Learn with us.

Thanks,
Brij

JavaScript Day : Presented on Arrays in JavaScript

Hi All,

We had organized again a very successful event at C# Corner Delhi Chapter meet fifth times in a row. This was named as JavaScript Day and attended by more that 120 attendees . The entire day we discussed on Core JavaScript and we’ll cover more topics in coming monthly meet.

I discussed on JavaScript array and covered the following topics.

Continue reading

Inheritance with JavaScript

This post is in continuation in my last post.  In my last post, I discussed various ways to create custom object in JavaScript. I’ll advise you to go through that if you didn’t get a chance to have a look then you can go through it. Please find the link below

Various ways to Create custom objects in JavaScript

In this post, We will discuss, how we can use other features of Object Oriented concepts in JavaScript. Today I’ll discuss one of the main concepts of Object Orient Programming that is Inheritance.

So how can we use Inheritance with JavaScript ?

Various ways and plugins are available that provides similar ways to use Inheritance that we have used in other object oriented language. But the prototype based Inheritance is used most.

JavaScript is a object based language that is based upon Prototype based programming. It is free from Class and completely rely on objects only .

Did you hear earlier  that What is Prototype based language or what is Prototype based programming?

I would say this is just another way to provide object oriented feature by a language. As per wiki

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming”.

So let’s start learning. To create a Class in JavaScript, we are required to create a function  that we also used to call a Constructor. I’ll use the word constructor in my further discussion. So Let’s create a Constructor called person

         function Person() {
             this.ToString = function () { alert('I am a Person'); }
             this.DisplayResidence = function () { alert('I stay near my office'); }
         }

As in my last post, I mentioned that Person is a nested function. As you can see that here we have following two functions in the Person constructor.

  1. ToString
  2. DisplayResidence

So let’s create a new object and display it

function DisplayObject()
{
var objPerson = new Person(); // Line- 1 Creates the instance of Person
objPerson.ToString();  // Line- 2
objPerson.DisplayResidence(); // Line- 3
}

Here both display as expected . Line 2 - I am a Person and Line 3 - I stay near my office

Now let’s say we want to create a constructor Employee as

         function Employee() {
             this.ToString = function () { alert('I am an employee'); }
             this.DisplayRole = function () { alert('My role is development and implementation'); }
         }

As you can see it has two methods ToString and DisplayRole. Now how can Employee inherit the properties/methods of Person. It can be done by writing as

Employee.prototype = new Person();

Now the employee has the properties of person as well. Now it has three methods

  • ToString()
  • DisplayResidence()
  • DisplayRole()

Let’s examine it by the method

         function DisplayObject() {
                var objPerson = new Person(); // Line- 1: Calles constrouctor Person to create an instance and assign it to objPerson
                objPerson.ToString(); // Line- 2: Calles ToString method of Person
                objPerson.DisplayResidence(); // Line- 3: Calles ToString method of Person

                var objEmployee = new Employee();  // Line- 4: Calles constrouctor Employee to create an instance and assign it to objEmployee
                objEmployee.ToString(); // Line- 5: Calles ToString method of Person
                objEmployee.DisplayResidence(); // Line- 6:  Calles ToString method of Person
                objEmployee.DisplayRole(); // Line- 7:  Calles ToString method of Person

                alert(objPerson instanceof Person);  // Line- 8:  Checks the type of objPerson
                alert(objEmployee instanceof Person);  // Line- 9:  Checks the type of objEmployee
         }

Let’s discuss it by Line numbers

Line 2 and Line 3- same as discussed above

Line 5- What it will display ? It displays I am an employee because ToString is available at both current and parent. But because the objEmployee holds the instance of derived class so the overridden method is called.

Line 6- Here DisplayResidence is not defined in Employee so it calls the base class(Person) method and displayed.

Line 7-  DisplayRole is added in Employee object only and it shows ‘My role is development and implementation‘.

Line 8 – To check more on the type I added the last two lines. As objPerson is instance of Person only so it shows true.

Line 9 – As Employee inherits Person so it also shows true but if you delete the below line ….

<br />Employee.prototype = new Person();<br />

then it’ll show false as it does not inherit person any more.

Now you must have got enough Idea about prototype based inheritance in JavaScript.

There is one more way to add a method to and existing constructor as Person has two methods and  that we defined as nested class. You can write that in the following way as well

         function Person() {
         }
         Person.prototype.ToString = function () { alert('I am a Person'); }
         Person.prototype.DisplayResidence = function () {alert('I stay near my office');}

Now the question arises,  how Inheritance works in JavaScript.

Whenever we create an instance using the new Operator, It creates all the properties/methods and also has internally a variable called __proto__ (double underscore at both side) this is the variable which is responsible for the inheritance feature. So let’s say I created a instance of Employee as

var objEmployee = new Employee();

It’ll be having two methods/properties as defined and on __proto__ as

  1. ToString
  2. DisplayRole
  3. __proto__

Just because I have written also as

Employee.prototype = new Person();

The __proto__ variable gets assigned to the person instance. This __proto__ used to determine the prototype chain and return the property values. This allows us to access the base class methods and public properties.

As I talked about prototype chain, means as soon as I assign

Employee.prototype = new Person();

a __proto__ variable gets available to us that can be be further used for inheritance. So lets create another constructor as

         function TeamLead() {
             this.ToString = function () { alert('I am a Manager.'); }
             this.DisplayRole = function () { alert('I rarely code but do lot of code reviews'); }
             this.DisplayMeetings = function () { alert('I have 3 meetings scheduled daily'); }
         }

Now as soon as I’ll create an instance using new operator then instance will be have the properties

  1. ToString
  2. DisplayRole
  3. DisplayMeetings
  4. __proto__

Now if we write the code for inheritance as

TeamLead.prototype = new Employee();

It can access all the properties in the hierarchies. We can check the type of instances as

 function DisplayObject() {
             var objTeamLead = new TeamLead();
             alert(objTeamLead instanceof Person);  // returns true because TeamLead inherits base class Person
             alert(objTeamLead instanceof Employee);  // returns true because TeamLead inherits  base class Employee
             alert(objTeamLead instanceof TeamLead); // returns true as expected
             }

You can see the results and they are expected

Let’s see the prototype chain as discussed earlier

         function DisplayObject() {
             var objTeamLead = new TeamLead();

             // Also here I'll show, How the prototype chain works
             alert(objTeamLead.__proto__ == TeamLead.prototype); // returns true because it represents the same prototype
             alert(objTeamLead.__proto__.__proto__ == Employee.prototype);  // returns true because second level __proto__ belongs to Employee.prototype
             alert(objTeamLead.__proto__.__proto__.__proto__ == Person.prototype);  // returns true because third level __proto__ belongs to Employee.prototype
         }

As you can see that actually __proto__ variable is actually the key for the inheritance.

Now you all must have got enough Idea about Prototype based programming and how we can use inheritance with JavaScript.

Do share your feedback.

Happy Coding,
Brij

Various ways to Create custom objects in JavaScript

Hi All,

Many developers still put their data at client side in multiple variables and some times it becomes very tough to manage them. If we store the data in object format then it becomes very easy to manage and control it. We can have similar model as we use at server side, it provides consistency of the data model in our application.

So today we’ll see various ways to store the data in Object format at Client side.

A Simple way:

We can create a normal object and can encapsulate related data in a single object. To create  a simple object, you just need to assign a variable with new Object() and create the properties according to our requirement and assign the values as

 var person = new Object();
 person.FirstName = "Brij";
 person.LastName = "Mishra";
 person.Age = 27;

This is a simple object with few properties like FirstName, LastName and Age. You can read the object as

function displayObject() {
      alert(person.FirstName + " " + person.LastName);
      alert("Age: " + person.Age);
}

Here as you can see it is an object which contains the details of an person but here we didn’t define any class (as we do in C#) then we create an object assign some values in that. But we just created a object and created properties on the fly. Now obviously, while reading the object, you  might not get any intellisense on some editor and we need to remember the name of the properties. And if we wrongly typed the property name then we’ll get an error at run time.

Because JavaScript is loosely coupled language. There is no way if we create similar object and check whether they are similar type of object. Also it is impossible to identify  the object that you are using is actually of what type.

But there are more standard ways to Create a Type. We’ll discuss in coming section. First, we are going to discuss

Closure
Closure is function that encapsulate a class. Actually closure is not a normal function but it contains other functions and you can say it is a nested function. Inner functions actually constitutes its properties and methods. It provides an elegant way to create multiple instances of a type like person. It provides exactly similar behavior like class and object. Let’s create a closure

        function Person(fisrtName, lastName, age) {
            var _firstName = fisrtName;
            var _lastName = lastName;
            var _age = age;

            this.set_FirstName = function (fisrtName) {
                _firstName = fisrtName;
            }
            this.get_FirstName = function () {
                return _firstName;
            }
            this.set_LastName = function (lastName) {
                _lastName = lastName;
            }
            this.get_LastName = function () {
                return _lastName;
            }
            this.set_Age = function (age) {
                _age = age;
            }
            this.get_Age = function () {
                return _age;
            }
        }

Now let’s use the person and person instantiate it. As you can see that it is taking three parameters, fisrtName, lastName and age. So you need pass the values while instantiating it. Using it, you can create an instance similar like C# as

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see, How I created instance. I have created a setter and getter to set and get the properties.

Lets’s discuss another way.

Prototype:

Prototypes provides another way to create custom objects in JavaScript. Every JavaScript object has public prototype property . This actually exposes the public interface of the object. Using this feature, we can add some public properties and methods to a JavaScript object. Let’s see it with example

        Person = function (firstName, lastName, age) {
            this._firstName = firstName;
            this._lastName = lastName;
            this._age = age;

            Person.prototype.set_FirstName = function (firstName) {
                this._firstName = firstName;
            }
            Person.prototype.get_FirstName = function () {
                return this._firstName;
            }
            Person.prototype.set_LastName = function (lastName) {
                this._lastName = lastName;
            }
            Person.prototype.get_LastName = function () {
                return this._lastName;
            }
            Person.prototype.set_Age = function (age) {
                this._age = age;
            }
            Person.prototype.get_Age = function () {
                return this._age;
            }
        }

So you can see that person is assigned to a function which is actually also a nested function but it is uses prototype property of an object. Lets instantiate it and check it.

function DisplayClosure() {
        function DisplayClosure() {
            var person = new NewPerson("Brij", "Mishra", 27);

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());

            person.set_FirstName("Rahul");
            person.set_LastName("Khanna");
            person.set_Age("30");

            alert(person.get_FirstName() + " " + person.get_LastName());
            alert("Age: " + person.get_Age());
        }

So you can see that this also is used in the similar way as Closure.
So what are the benefits of prototypes over closure. There are many..

  • Prototypes provide better support for Intellisense and debugging.
  • Prototypes also provide better performance in several browsers.
  • Prototypes support reflection and that’s why used a lot in ASP.NET AJAX.
  • Closure does not create an instance, it just specialized members to your object. instanceof does not work with Closure. While Prototype configured once then copied to every instance created using new.

Hope you all like it.

Cheers,
Brij

How to access the input control’s data at Server side during Client Callback : A useful trick

Client callback is one way to update the webpage without performing the full page postback. It maintains the Client state while updating the Webpage. During Client callback the webpage runs through modifies version of Page Life Cycle.

The LifeCycle of a page in Client Call Back is  as

Page Lifecycle iin Callback

If you want to learn  more about Client Callback, click here.

But the main drawback of  Client Callback, The input data is not posted from Client to Server. Also,  It does not maintain the view state during partial postback as you can see the Page life cycle of Client callbak it is not saved or SaveViewState event is not fired.

Lets see it with an example.

I have created a simple form to collect some information of an person data. And it has a submit button, which initiates a Callback. As

 <table>
 <tr><td><asp:Label id="lblFName" runat="server" Text="First Name" /> </td>
 <td><asp:TextBox ID="tbFName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblMName" runat="server" Text="Middile Name" /> </td>
 <td><asp:TextBox ID="tbMName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblLName" runat="server" Text="Last Name" /></td><td><asp:TextBox ID="tbLName" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblAge" runat="server" Text="Age" /></td><td><asp:TextBox ID="tbAge" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblMailId" runat="server" Text="Email" /></td><td><asp:TextBox ID="tbEMail" runat="server"></asp:TextBox></td></tr><tr>
 <td><asp:Label id="lblSex" runat="server" Text="Sex" /></td><td><asp:TextBox ID="tbSex" runat="server"></asp:TextBox></td></tr><tr>
 <td colspan="2"><input id="btnCallBack" type="button" value="Submit" onclick="InitiateCallBack();"/></td></tr>
</table>

Server side code is as

public partial class Callback : System.Web.UI.Page,ICallbackEventHandler
{
    string result;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsCallback)
            return;
        //Creating a reference of Client side Method, that is called after callback on server
        String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg",
            "ReceiveServerData", "");

        //Putting the reference in the method that will initiate Callback
        String callbackScript = "function CallServer(arg, context) {" +
            cbReference + "; }";

        //Registering the method
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            "CallServer", callbackScript, true);
    }
    public void RaiseCallbackEvent(String eventArgument)
    {
        string firstName = tbFName.Text;
        //Read other data as well

    }
    public string GetCallbackResult()
    {
        return result;
    }
}

And the client side method is

function InitiateCallBack() {
     //Intiate the callback
     CallServer("",'');
}

// Called after the server side processing is done
function ReceiveServerData(arg, context) {
    //arg: hold the result
    //Updating the UI
    document.getElementById('divCallbacl').innerHTML = arg;
}

After filling this form, I submitted it. Now if you try to access the entered using control’s property, you would not get it.

Let’s dig it more and check the form collection, whether the data is passed from Client to server or not

So as you can see that the data is not passed in form collection

But let’s put the following lines of code in java-script, just before initiating the call for Callback as

 function InitiateCallBack() {
	__theFormPostCollection.length = 0;
        __theFormPostData = "";
        WebForm_InitCallback();

        //Intiate the callback
        CallServer("",'');
}

Now let’s run the code and submit the form as earlier.

Now let’s check the form collection.

What a surprise, we got all the input data in form collection. That’s nice.

Now access the data using control’s property.

and you got it.

Now let’s try to see, what does the extra lines of code does

//This Clear the earlier the old data in form collection.
__theFormPostCollection.length = 0;
//It sets the forms data to empty
__theFormPostData = "";
//This method builds the body of the POST request when the page loads. The body of the page is a string 
//(that is __theFormPostData) filled with the contents 
of the view state and all of the input fields in the form.
WebForm_InitCallback();

But I would suggest to use these line at caution. Use only when you need to collect the update from Page during Callback. If you don’t need to get some data or it is in readonly page, don’t use it it introduce extra overhead to your page and costs at performance point of view.

Hope you  all have enjoyed the post.

Page.ClientScript.RegisterStartupScript is not working : A Solution

This is going to be a very short post but will be useful many developers.

You have registered some JavaScript block from server side. But it’s not working. Actually it’s not getting rendered on Client side when you see the PageSource. But the same code works in different projects/applications/pages. Say you have code like this

           Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowStatus", "javascript:alert('Record is not updated');", true);
 

It is registering one one startup script that will be fired when the page will be loaded.
Say you have used at several time and it was working but now it is failing.  Similarly Page.ClientScript provide many other methods that will also not work.

One of the main reasons is, We start using Ajax on our pages. Ajax requires a ScriptManager to handle all the ajax related (Partial postback) tasks. Ajax requires lots of JavaScript code that is managed by the ScriptManager. And it must be noted on a single page only one instance of ScriptManager is allowed.

So whenever we have an instance of  ScriptManager on our page, we need to register the Script using ScriptManager. So you need to change the code like this

            ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowStatus", "javascript:alert('Record is not updated');", true);

       

Now this code make the script start working. Similarly , we also need to change other Page.ClientScript methods to appropriate ScriptManager method.

Cheers,

Brij

Validating partial page with ASP.NET Validators using JavaScript

Validation plays a key role whenever we take a inputs from the user. For this, ASP.NET provides us few validator controls that are used a lot in web applications.
Now a days, in our application, we used to have several section in our web pages.
And also, we populate some data based on the user’s input.
So several times, it requires  to validate the page partially not the entire page,
while earlier we used to have single submit button and their we need to validate the page.

AJAX also played a key role, for partial post back, initiate a call to server etc, which requires to validate a part of the page.

So in these scenarios our earlier approach of validation would not work.
In this kind of scenario, I will discuss few things that will be very helpful.

First, I would suggest, to divide your page in some logical section, those you might need to validate at certain points. And assign a different group name to the validators on those section.

1) If you are initiating an ajax call or initiating a callback from java-script, and you want to validate certain section/part of the page.

So before initiating the ajax call, you need to validate the user inputs. This can be easily with the following method.

You need to call Page_ClientValidate() method, this method has two flavors,
- Page_ClientValidate() it fires all the validators on the page and returns false, if it fails
- Page_ClientValidate(‘groupname’), this method fires all the validators having the passed groupname and returns false if any validator fails.
This is quite useful, while validating partial section/part of the page. So your java script code may look like this

function SaveAddress()
{
	if(Page_ClientValidate('groupname') == false)
		return false;
	else
	{
		//Save Address
	}
}

2) Several time, it happens, that based on some requirement, we used to hide some section of input form or hide some input control, but whenever page/section is going to be submitted, the hidden validators also gets fired. So to overcome this problem, you may need to disable the validators. So to disable any validator from javascript as

document.getElementById('ValidatorClientId').enabled=false;

So these validator wont be fired till you gain enable it. You can enable it as

document.getElementById('ValidatorClientId').enabled=true;

Hope you all will like this post and will found it to be useful.

Why MaxLength property of a textbox with multiline mode doesn’t work? A Solution

Many developers set the MaxLength property of a Textbox and it works fine until the Textbox is not in multiline mode, which is by default behavior of a Textbox.

So what is the basic diffference between a textbox in single line and multiline mode!!!

Let’s see, how it gets rendered as html. Lets have a look

Textbox with SingleLine mode

Textbox with SingleLine mode

Now Textbox with MultiLine mode

Textbox with MultiLine mode

Textbox with MultiLine mode

As you can see, When a Textbox is in SingleLine mode, it gets rendered as a input type text  and when it is in MultiLine mode, it gets rendered as a textarea. As we know MaxLength property works only for input type.

So what is the solution. We need to have a custom solution for this.

Let’s try some solution,

One thing we can do, we can attach a function on onkeypress event to the textbox, which first check the length of input string and if exceed with limit it just returns else allow to enter any input. In the below example I have used the maximum length as 10.

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" onkeypress="return CheckLength();"></asp:TextBox>

//And the javascript code is
function CheckLength() {
            var textbox = document.getElementById("<%=tb.ClientID%>").value;
            if (textbox.trim().length >= 10) {
                return false;
            }
            else {
                return true;
            }
        }

This works fine until, a user doesn’t paste a text  which is greater than the max length that is given( here 10).  So there is no simple way to stop this. To overcome this problem, one should use one of the asp.net validators.

One can go for the custom validator, and provide a javascript function, which checks the length of the text and if exceeds the maxlength then show an error. Let’s see the code below

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" ></asp:TextBox>
//Validator
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please enter maximum 10 charachters." ControlToValidate="tb"
         SetFocusOnError="true" ClientValidationFunction="CheckMaxLength" ></asp:CustomValidator>

//Client Validator function
function CheckMaxLength(sender, args) {
            if (args.Value.trim().length >= 10) {
                args.IsValid = false;
            }
        }

But there is another smart way is there, to acheive this. We can also use Regular expression validator for this, which will check the count of the entered character and will throw an error if it exceeds. Here we would not require to write a javascript function. We need to have a regular expression that will work. Let’s see the code

<asp:TextBox ID="tb" runat="server" TextMode="MultiLine" ></asp:TextBox>

//Regular Expression validator
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="tb" ErrorMessage="Please enter maximum 10 charachters."
 SetFocusOnError="true" ValidationExpression="^[a-zA-Z.]{0,10}$"></asp:RegularExpressionValidator>

Here we don’t require to write a javascript function. I have used a regular expression ^[a-zA-Z.]{0,10}$, which allows all the characters with length 0 to 10.

Hope you all must have enjoyed.

Thanks,

Brij