Angularjs Validation with CSS and ngMessage with Demo

angularjs ngmessage example angularjs ng message ngmessages example ng-messages custom validation angularjs error message popup validate angularjs application in different ways angularjs validation demo

Angularjs ngMessage validation is so powerful that we can complete our validation without writing any code except two simple CSS class and with great look and feel. By using ngMessage we can give those features which was taking months to wring css and JavaScript but with angularjs it is only the elements settings. In this article we will first try to understand the very simple CSS style then we will see the ngMessage one in more detail with bootstrap nice messaging.

  • Validation with CSS
  • Validation with ngMessage

Validation with CSS Only

Angularjs use ng-valid and ng-invalid to show the valid or invalid values on the page. When we type something it keeps checking and changing these two and many other values. If we can write the CSS by using these two values we can achieve our goal easily.

Let's write a very simple and complete class for input of type text:

input[type=text].ng-invalid{
  border-left:solid 3px #900;
}
input[type=text].ng-valid{
  border-left:solid 3px #090;
}

These two classes will validate around 80 percent of our application but we need more like email, textarea and many more, for your understanding I am adding here two more type of controls, input of type email and textarea, here is the final code:

input[type=text].ng-invalid,
input[type=email].ng-invalid,
textarea.ng-invalid{
  border-left:solid 3px #900;
}
input[type=text].ng-valid,
input[type=email].ng-valid,
textarea.ng-valid{
  border-left:solid 3px #090;
}

Similarly we can add for number, date, select and any other type of control.

Angularjs Validation with css and two lines of code only

Now set the type of validation you want with every control say the customer name text box, here is the full HTML

<input type="text" class="form-control" 
    ng-model="customer.name"
    name="txtName" 
    ng-minlength ='3'
    ng-maxlength ='30'
    ng-required='true'
    placeholder="Customer Name" />

It is required, minimum 3 characters and maximum 30 characters long.

This will not stop the use to save the data by clicking the save button. There are two ways to stop the user to submit the page if page is not valid.

  • Disable the save button until the form is valid
  • Check in controller and return if form is not valid

To do so add a name to the form say frmCustomer.

If you don't want to disable the button then add these two lines in your save method in controller

 if (!$scope.frmCustomer.$valid)
    return;

Otherwise disable the Save button until form become valid, here is the save button code:

 <button type='submit' class='btn btn-success' 
    ng-disabled='!frmCustomer.$valid'> Save </button>

We are done, go ahead and check the Demo

Validation with ngMessage

Above CSS method work very nice but the problem is that, when a field is invalid due the length or format then it is not very clear why it is invalid. So by using ngMessage we are going to solve this problem as well.

To use ngMessage validation we need to add the JavaScript file `angular-messages.min.js' in our index page and need to adjust our module like this

 angular.module('myApp', ['ngMessages']);
  • We don't want to show all the messages on page load, not a good option
  • On click of save button all the invalid fields will start showing error message
  • If change any value and it is not valid then it will show the message
  • After saving the data, form will be again in pristine state (initial state) so you can enter a new record

Angularjs ngMessage validation: show error on save and change only

Too much talking, let's start coding it.

To show the message only for dirty fields we can use

ng-if='frmCustomer.txtEmail.$dirty'

To check for form is submitted or not we can use

ng-if='frmCustomer.$submitted'

To use both of them together we can use

ng-if='frmCustomer.txtEmail.$dirty  || frmCustomer.$submitted'

Let's see our Customer name text box first and it's validation:

 <input type="text" class="form-control" 
    ng-model="customer.name"
    name="txtName" 
    ng-minlength ='3'
    ng-maxlength ='30'
    ng-required='true'
    placeholder="Customer Name" />  

I make it required, give a name txtName, minimum and maximum length, so write the write the different message for different conditions

<span ng-messages="frmCustomer.txtName.$error" 
    ng-if='frmCustomer.txtName.$dirty  || frmCustomer.$submitted' role="alert">
    <span ng-message="required" class="error">Name is required</span>
    <span ng-message="minlength" class="error">Min. 3 Characters</span>
    <span ng-message="maxlength" class="error">Max. 30 Characters</span>
</span>

It will show the message if

  • txtName text box have any error and
  • user has change the value of text or
  • user has clicked the save button

After saving the data you might want to clear the form by code. If you will do so it will start showing all the messages, so to fix this you can pristine the form, here is the code just add it after cleaning the model:

$scope.frmCustomer.$setPristine();

Check the demo with working code

Ali Adravi Having 10+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 8 years and still with the same company. Always ready to learn new technologies and tricks.
  • angularjs
  • ngMessage
  • Validation
By Ali Adravi On 06 May, 16  Viewed: 660

Other blogs you may like

Angularjs powerful paging on table and searching with delay and demo

Paging on table is the basic requirement and most of us look for some grid so it can provide the complete feature of paging and sorting but in Angularjs it is so easy that anyone can achieve it by writing some code. I checked and found most of the available code give the paging feature in for 1 to... By Ali Adravi   On 14 Aug 2015  Viewed: 4,796

Angularjs Cascading Dropdown/Select with demo

Cascading dropdown with angularjs is easier than MVC and ASP.Net. In Angularjs ng-change is the best event to hook the function to get the second dropdown list items. In this article, we will try to fill the state dropdown on selection change of country and then fill the city dropdown on change... By Ali Adravi   On 06 Aug 2015  Viewed: 23,146

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 2

Add/Edid Customer in Modal Popup --- In previous article we discussed how to search, delete and show detail of customer and contact list. In this article we will try to open the modal popup to add new customer and edit an existing customer record. I divided article in two parts because of the... By Ali Adravi   On 29 Jul 2015  Viewed: 9,770

Custom Directives in AngularJS with example and demo

Angularjs custom directives are the common to avoid the duplicate code, it is easy powerful and really nice. There are already too many directive have been created by experts but as a developer we need to write our own to achieve our specific goal. ng-model, ng-if, ng-show, ng-repeat all these are... By Ali Adravi   On 29 Jul 2015  Viewed: 1,667

Angularjs CRUD with Web API, Entity Framework & Bootstrap modal popup part 1

Search sort Insert update and delete are the basic features we need to learn first to learn any language, In this article we will try to create these features with Web API, bootstrap modal popup and ui.router. We will use enetity framework code first to save and retrieve data from database. We... By Ali Adravi   On 28 Jul 2015  Viewed: 18,295