Part 6 - How to create simple registration form with validation using angularjs and mvc4.


In this post, I would like to explain Part 6 - How to create simple registration form with validation using angularjs and mvc4.
This is our 6th Post about AngularJS. Here I have explained a little about AngularJS and What we will learn in this section part by part.

In the previous example we have seen Part 3 - How to create a login page using AngularJS in MVC4 application
Here in this post I explained how can we create simple registration form with validation using angularjs and mvc4. As registration form is a very common form for Internet application, so I would like to create a simple registration form here to demonstrate validation and Save data to the database.

Steps :

Step-1: Create a table into the database.

Here I have modified existing created table named User (created at Part 3 of this series). I have added 2 new fields here Email ID and Gender.
Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-2: Update Entity Data Model.

Go to Solution Explorer > Open your Entity Data Model (here "MyModel.edmx") > Right Click On Blank area for Get Context Menu > Update Model From Database... > A popup window will come (Entity Data Model Wizard) > Select Tables > Finish.

Step-3: Add new action into your controller (here in the Data Controller) for Save Data to the Database.

Here I have added "Register" Action into "DataController". Please write this following code

             //Save Simple Registration Form
            public JsonResult Register(User u)
                string message = "";
                //Here we will save data to the database
                if (ModelState.IsValid)
                    using (MyDatabaseEntities dc = new MyDatabaseEntities())
                        //check username available
                        var user = dc.Users.Where(a => a.Username.Equals(u.Username)).FirstOrDefault();
                        if (user == null)
                            //Save here
                            message = "Success";
                            message = "Username not available!";
                    message = "Failed!";
                return new JsonResult { Data = message,  JsonRequestBehavior = JsonRequestBehavior.AllowGet };

Step-4: Add Validation attribute to the model for Server side validation.

             namespace MVCWithAngularJs
                using System;
                using System.Collections.Generic;
                using System.ComponentModel.DataAnnotations;
                public partial class User
                    public int UserID { get; set; }
                    [Required(ErrorMessage="Username required", AllowEmptyStrings=false)]
                    public string Username { get; set; }
                    [Required(ErrorMessage = "Password required", AllowEmptyStrings = false)]
                    public string Password { get; set; }
                    [Required(ErrorMessage = "Fullname required", AllowEmptyStrings = false)]
                    public string FullName { get; set; }
                    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage="Email ID not valid")]
                    public string EmailID { get; set; }
                    [Required(ErrorMessage = "Gender required", AllowEmptyStrings = false)]
                    public string Gender { get; set; }


Step-5: Add a new js File for add a new AngularJS controller and a Factory

Go to Solution Explorer > Right Click on folder (where you want to saved your AngularJS controller files, here I have created a folder named "AngularController"  under Scripts Folder) > Add > Select Javascript file > Enter name > Add.

Write following code in this file.

             angular.module('MyApp') //extending angular module from First Part
            .controller('Part6Controller', function ($scope, RegistrationService) { //explained about controller in Part 2
                //Default Variable
                $scope.submitText = "Save";
                $scope.submitted = false;
                $scope.message = '';
                $scope.isFormValid = false;
                $scope.User = {
                    Username : '',
                    Password: '',
                    FullName: '',
                    EmailID: '',
                //Check form Validation // here f1 is our form name
                $scope.$watch('f1.$valid', function (newValue) {
                    $scope.isFormValid = newValue;
                //Save Data
                $scope.SaveData = function (data) {
                    if ($scope.submitText == 'Save') {
                        $scope.submitted = true;
                        $scope.message = '';

                        if ($scope.isFormValid) {
                            $scope.submitText = 'Please Wait...';
                            $scope.User = data;
                            RegistrationService.SaveFormData($scope.User).then(function (d) {
                                if (d == 'Success') {
                                    //have to clear form here
                                $scope.submitText = "Save";
                        else {
                            $scope.message = 'Please fill required fields value';
                //Clear Form (reset)
                function ClearForm() {
                    $scope.User = {};
                    $scope.f1.$setPristine(); //here f1 our form name
                    $scope.submitted = false;
            .factory('RegistrationService', function ($http, $q) { //explained about factory in Part 2
                //here $q is a angularjs service with help us to run asynchronous function and return result when processing done
                var fac = {};
                fac.SaveFormData = function (data) {
                    var defer = $q.defer();
                        url: '/Data/Register',
                        method: 'POST',
                        data: JSON.stringify(data),
                        headers: {'content-type' : 'application/json'}
                    }).success(function (d) {
                        // Success callback
                    }).error(function (e) {
                        //Failed Callback
                    return defer.promise;
                return fac;


Here I have created an angular controller named "Part6Controller" and a Factory named "LocationService" with $http injected service. I have explained a little about AngularJS controller here, about Factory here and about $http here.
here you can see I have used $q, this is a angularjs service with help us to run asynchronous function and return result when processing done.
We will see more about $q later.

Step-6: Add new action into your controller (here in the HomeController) for Get the View for implement registration form.

Here I have added "Part6" Action into "Home" Controller. Please write this following code

            public ActionResult Part6() // Implement Cascade dropdownlist
                return View();

Step-7: Add view for the Action & design.

Right Click on Action Method (here right click on Part6 action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
Complete View
                ViewBag.Title = "Part6";
                    border:1px solid #A5A5A5;
                    border:1px solid red;
                    background-color:rgb(255, 244, 244);
                .error {
            <h2>Simple Registration Form</h2>
            <div ng-controller="Part6Controller">
                <form novalidate name="f1" ng-submit="SaveData(User)">
                    <div style="color:red">{{message}}</div>
                            <td>Full Name : </td>
                                <input type="text" ng-model="User.FullName" name="uFullName" ng-class="submitted?'ng-dirty':''" required autofocus />
                                <span class="error" ng-show="(f1.uFullName.$dirty || submitted) && f1.uFullName.$error.required" >Fullname required!</span>

                                <!-- here (f1.uFullName.$dirty || submitted) means if submit button clicked or it is dirty -->
                            <td>Email ID : </td>
                                <input type="email" ng-model="User.EmailID" name="uEmailID" ng-class="submitted?'ng-dirty':''" /> <!-- Not required-->
                                <span class="error" ng-show="(f1.uEmailID.$dirty || submitted) && f1.uEmailID.$">Email ID not valid!</span>
                                @* here f1.uEmailID.$ will check is provided email id valid or not *@
                            <td>Username : </td>
                                <input type="text" ng-model="User.Username" name="uUsername" ng-class="submitted?'ng-dirty':''" required />
                                <span class="error" ng-show="(f1.uUsername.$dirty || submitted) && f1.uUsername.$error.required">Username required!</span>
                            <td>Password : </td>
                                <input type="password" ng-model="User.Password" name="uPassword" ng-class="submitted?'ng-dirty':''" required />
                                <span class="error" ng-show="(f1.uPassword.$dirty || submitted) && f1.uPassword.$error.required">Password required!</span>
                            <td> Gender : </td>
                                <input type="radio" ng-model="User.Gender" name="uGender" value="Male" required /> Male
                                <input type="radio" ng-model="User.Gender" name="uGender" value="Female" required /> Female
                                <span class="error" ng-show="(f1.uGender.$dirty || submitted) && f1.uGender.$error.required">Gender required!</span>
                                <input type="submit" value="{{submitText}}" />

            @section Scripts{
                <script src="~/Scripts/AngularController/Part6Controller.js"></script>


Step-8: Run Application.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms,, sql server, entity framework, Ajax, Jquery, web api, web service and more.