Skip to main content

Asp.Net Core MVC Form Validation Techniques


Introduction:

Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library jQuery Validate.

In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples.

Getting Started:

Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio.

Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as below.
PersonController.cs:
using Microsoft.AspNetCore.Mvc;
namespace MvcValidation.App.Controllers
{
    [Route("person")]
    public class PersonController : Controller
    {
        [HttpGet]
        [Route("create")]
        public IActionResult Create()
        {
            return View();
        }
    }
}
Add MVC View name as 'Create.cshtml' which is furnished with a form to validate.
Views/Person/Create.cshtml:
@model Person

<div>
    <form asp-action="create-post">
        <div class="form-group row">
            <label asp-for="Name" class="col-sm-2 col-form-label">Name</label>
            <div class="col-sm-10">
                <input asp-for="Name" type="text" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group row">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>

'Person' will be the model for the 'Create.cshtml' view. In the form, we can observer MVC Tag Helpers like 'asp-action', 'asp-for', 'asp-validation-for' will be discussed in much more details in later steps.

Now Add Model 'Person.cs' which binds or holds the form data.
Models/Person.cs:
using System.ComponentModel.DataAnnotations;
namespace MvcValidation.App.Models
{
    public class Person
    {
        public string Name { get; set; }
    }
}
Now Observer Html above, MVC Tag Helpers value assigned is "Name" which is from the 'PersonModel'. Similarly, we have to bind properties from model class with the Html to consume the validation benefits provided by Dotnet Core.

Now run the application and navigate to "https://localhost:44397/person/create"
Now open browser developers tools and observe the Html rendered inside form where we can see some 'data-{something}' attributes, id's, the name's are rendered. If you wondered how this happens, then the answer will be MVC Tag Helpers.

Configure Server-Side Validations:

Asp.Net Core MVC server-side validation done by Data Annotations in which the properties for the form need to configure validation, those properties will be decoration with validation Attribute. Here are some built-in validation attributes provided by Dotnet Core:
  • [Compare] - validates two properties of a model match.
  • [EmailAddress] - validates that the property has a valid email format.
  • [Phone] - validates that the property has a valid phone number format.
  • [Range] - validates that the property value fallen within the specified range values.
  • [RegularExpression] - validates that the property has satisfied the given regular expression.
  • [Required] - validate that the property has some value, can not be null or empty.
  • [StringLength] - validate that the property value length should not exceed the length specified.
  • [Remote]- validates the input on the client, by calling the action method on the server through AJAX.
These Attribute [AttributeName(ErrorMessage= "custom message")] might allow optional input parameters to override default functionality, for example, they allow us to input error message to override the default one.

Let's add [Required] attribute to 'Name' property in Person Model. Update the code as below
Models/Person.cs:
[Required]
public string Name { get; set; }
Now Test the sample application again and open browser developer tools then inspect the form element. We can observe after adding validation attribute, in the Html input field two more 'data-{something}' attributes are added like 'data-val' and 'data-val-required'.
Now add a new action method that receives the form posted data and validates the form data. Update the code as below
PersonController.cs:
[HttpPost]
[Route("create-post")]
public IActionResult Create(Person person)
{
 if (!ModelState.IsValid)
 {
  return View(person);
 }
 return Content("Success");
}
  • In this Post action method, model validation can be check by using 'ModelState' which depends on the form model (our example Person.cs is form model). 
  • If model valid we returning some success string (in the real-time application based on the application requirement redirected to success view ) if validation fails then pass the model to view 'Create.cshml'. Because we are passing the model object which is invalid passing to the 'create.cshml', now the error messages will be displayed.
Now run the application, navigate to "https://localhost:44397/person/create" and submit the form with empty fields, now page gets reloaded and posted the form to 'create-post' route action method since validation fails page gets rendered as below.
Now open browser developers tools, and observe form tag, in that observe span tag which displays an error message. If you recall on form load check the span tag value which is empty because on form get action method we are not passing any 'Person' model. But if you submit a form to post action method where we passing model to view then we are seeing an error message rendered by the server.
Remember in this approach validation done by the server, so on every submission entire form gets posted to a server and reloads the page. So for every invalid form submission application will participate in reloading page.

Client Validation Using jQuery Unobtrusive Validation:

jQuery Unobtrusive Validation is a front-end validation library developed Microsoft. Using client-side validation benefits the application by reducing its number of round-trips to the server. Validating page without reloading page also looks like much more user-friendly applications.

  • Most work of this jQuery Unobtrusive Validation depends on the Html data attributes (like 'data-{someAttribute}' ). 
  • jQuery Unobtrusive Validation parses the data- attribute and passes the logic to jQuery validation. 'data-value' attribute set true( means 'data-val = true') makes the field is ready or configured to get validated by jQuery Unobtrusive Validation. 
  • When the field is ready to validate, the field must also contain data- attribute rule means 'data-val-ruleName' and value for this attribute will be the error message for this validation. 
  • jQuery Unobtrusive Validation has been configured to deal with some default data- attribute rules (one example like data-val-required=" filed must be required").
  • The field can contain additional values while validating can be passed via data- attribute rule parameter(like 'data-val-rulename-parameter1='5'')
  • Note:- From the above points we conclude that data- attributes used by jQuery Unobtrusive Validation, either we have to write every attribute manually on Html or if we can recall this article MVC Tag Helpers like 'asp-for', 'asp-validation-for' are helping to generates data- attributes dynamically on rendering the page.
Now to consume jQuery Unobtrusive Validation, when we create Asp.Net Core MVC template Project it's automatically adding those files in '_ValidationScriptsPartial.cshtml'.
Views/Shared/_ValidationScriptsPartial.cshml:
Now load this partial script on to the 'Create.cshmtl' as below
Create.cshtml:
@section  Scripts{

@await Html.PartialAsync("/Views/Shared/_ValidationScriptsPartial.cshtml")
}
Now let's add data- attributes in the form manually, update the input field in the form as below
Create.cshtml:
<div class="col-sm-10">
 <input type="text" class="form-control input-validation-error" 
 data-val="true" 
 data-val-required="The Name field is required." 
 id="Name" name="Name" value="">
 <span class="text-danger field-validation-error" 
 data-valmsg-for="Name" 
 data-valmsg-replace="true">The Name field is required.</span>
</div>
Here I'm applying 'required' data- attribute rule which is default validation rule in jQuery Unobtrusive Validation library.

Let's disable the server-side validation by removing the [required] attribute on 'Name' property in the 'Person' Model
//[Required]
public string Name { get; set; }
Now if we test the application, validation will take place in the browser without posting the form to the server.

Need Both Client And Server-Side Validations? :

I suggest having both client and server-side validation makes a more assured way of submitting form data. Client-side validation really cut down a lot of server round-trips and looks more user-friendly. But there might be chances of by-passing client validations and submit data at times server-side help to guard.

Let's enable both client-side and server-side validation in our sample. Update the code as follows
Views/Person/Create.cshtml:
<label asp-for="Name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
 <input asp-for="name" type="text" class="form-control" />
 <span asp-validation-for="name" class="text-danger"></span>
</div>
Models/Person.cs:
[Required]
public string Name { get; set; }
Now if you test application, validation will be done by the browser. Let's by-pass javascript by blocking in the browser and now if you test validation will be done at the server-side. So we can understand how cool it is having both client-side and server-side validations.

Block javascript in chrome browser:
Now test application, client-side validation fails since script blocked on the browser, page reload then form gets validated at the server.

Custom Attribute Validation:

We can write custom validation to implement our own logic. This custom validation can be done at the entire model level or particular property in the model. Here we are going to create a property level validation. For our sample, I'm creating a custom validation attribute for the input field value that should match with the string specified in the server.

Attributes/TextMatchAttribute.cs:
using System.ComponentModel.DataAnnotations;
using MvcValidation.App.Models;

namespace MvcValidation.App.Attribute
{
    public class TextMatchAttribute:ValidationAttribute
    {
        public string ExpectedText { get; set; }
        public TextMatchAttribute(string expectedText)
        {
            ExpectedText = expectedText;
        }
        
        public string GetErrorMessage() => $"Enter value should always be {ExpectedText}";

        protected override  ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var person = (Person)validationContext.ObjectInstance;
            if(string.IsNullOrEmpty(person.Name) || person.Name.ToLower() != ExpectedText.ToLower())
            {
                return new ValidationResult(GetErrorMessage());
            }
            return ValidationResult.Success;
        }
    }
}
Our TextMatchAttribute implement ValdiationAttribute (provide by DataAnnotation), then overrides IsValid() method where we write own logic for validation. This custom attribute takes input string, so the user entered value in the form must match with this string.

Now use this custom attribute for 'Name' property in the 'Person' model class.
Models/Person.cs:
[TextMatch("Naveen")]
public string Name { get; set; }
Now test the application and navigate to "https://localhost:44397/person/create" and try to submit the form. You may wonder no client-side validation fired, immediately after hitting submit button page get post server(round-trips) and get server-side validations.

Client-Side Custom Validations:

Let's start by checking input field Html by opening developer tools as below
No data- attributes on the input field, will explain two conclusions. The first thing for custom validation attributes MVC Tag Helper has no idea of which type of data- attributes to be generated. The second thing is jQuery Unobtrusive Validation library contains all default attributes rule names like 'require', 'compare', etc so this explains they don't know how to deal with custom attributes.

Let's update the Html by adding data- attribute manually as below
Views/Person/Create.cshtml:
<div class="form-group row">
 <label asp-for="Name" class="col-sm-2 col-form-label">Name</label>
 <div class="col-sm-10">
  <input asp-for="Name"
      data-val="true"
      data-val-textMatch="Enter value should always be Naveen"
      data-val-textMatch-expectedText="Naveen"
      type="text" class="form-control" />
  <span asp-validation-for="Name" class="text-danger"></span>
 </div>

</div>
  • data-val="true" enables field is ready to validate
  • data-val-textMatch here 'textMatch' is the validation rule that needs to be registered in jQuery Unobtrusive Validation.
  • data-val-textMatch-expectedText here 'expectedText' are like additional parameters in 'textMatch' validation rule
Now we need to write a custom javascript validation and register those methods with jQuery Unobtrusive Validation with data- attribute rule name. Add new js file to hold custom javascript logic
wwwRoot/js/customValidation.Js:
$.validator.addMethod('textMatch', function (value, element, params) {
    var txtValue = $(params[0]).val();
    console.log(txtValue);
    var expectedText = params[1];
    console.log(expectedText);

    if (!txtValue || !expectedText) {
        return false
    }

    return txtValue.toLowerCase() === expectedText.toLowerCase();
});
Here method with data- attribute rule name added to jQuery Unobtrusive Validation. This method holds the logic to custom validation.

Now we need to register this method in jQuery Unobtrusive Validation adaptors as below
wwwRoot/js/customValidation.js:
$.validator.unobtrusive.adapters.add('textMatch', ['expectedText'], function (options) {
    var element = $(options.form).find('input#Name');

    options.rules['textMatch'] = [element, options.params['expectedText']];
    options.messages['textMatch'] = options.message;
});
Views/Person/Create.cshml:
@section Scripts{

    @await Html.PartialAsync("/Views/Shared/_ValidationScriptsPartial.cshtml")
    <script src="~/js/customValidation.js"></script>
}
Now test the application and our form gets validated on client-side without making round-trips to server for validations

Generate data- Html Attributes For Custom Validation  Attributes From Server:

If we recall for Custom Validation for client-side we have added data- Html attributes manually. This can be done from the server-side dynamically with the following 2 approaches.
  • Using AttributeAdapterBase<TAttribute>
  • Using IClientModelValidator

Generate data- Html Attributes Using AttributeAdapterBase:

Attributes/TextMatchAttributeAdapter.cs:
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Localization;

namespace MvcValidation.App.Attribute
{
    public class TextMatchAttributeAdapter : AttributeAdapterBase<textmatchattribute>
    {
        public TextMatchAttributeAdapter(TextMatchAttribute attribute, IStringLocalizer stringLocalizer):base(attribute, stringLocalizer)
        {

        }

        public override void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-textMatch", GetErrorMessage(context));
            MergeAttribute(context.Attributes, "data-val-textMatch-expectedText", Attribute.ExpectedText);
        }

        public override string GetErrorMessage(ModelValidationContextBase validationContext)
        {
            return Attribute.GetErrorMessage();
        }
    }
}
  • AttributeAdopterBase<TAttribute> is extended from Microsoft.AspNetCore.Mvc.DataAnnotations. 
  • The type of this Adapter is our custom validation Attribute. 
  • An override method 'AddValidation' is the place where we add our data- attributes render dynamically on page load
To create the instance of the validation attribute adapter, we need to register it under provider a class that implements Microsoft.AspNetCore.Mvc.DataAnnotations.IValidationAttributeAdapterProvider.
Attributes/CustomValidationAttributeAdapterProvider:
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.DataAnnotations;
using Microsoft.Extensions.Localization;

namespace MvcValidation.App.Attribute
{
    public class CustomValidationAttributeAdopterProvider: IValidationAttributeAdapterProvider
    {
        private readonly IValidationAttributeAdapterProvider baseProvider = new ValidationAttributeAdapterProvider();
        public IAttributeAdapter GetAttributeAdapter(ValidationAttribute attribute, IStringLocalizer stringLocalizer)
        {
            if(attribute is TextMatchAttribute textMatchAttribute)
            {
                return new TextMatchAttributeAdapter(textMatchAttribute, stringLocalizer);
            }
            return baseProvider.GetAttributeAdapter(attribute, stringLocalizer);
        }
    }
}
Now register this provider class in the ConfigureServices method in Startup.cs
Startup.cs:
services.AddSingleton<IValidationAttributeAdapterProvider, CustomValidationAttributeAdopterProvider>();
Now remove all manually added data- attributes for custom validations from the Html as below
Views/Person/Create.cshml:
<div class="form-group row">
 <label asp-for="Name" class="col-sm-2 col-form-label">Name</label>
 <div class="col-sm-10">
  <input asp-for="Name" type="text" class="form-control" />
  <span asp-validation-for="Name" class="text-danger"></span>
 </div>

</div>
Now run the application and open developer tools then inspect elements, we can observe data- attributes for custom validation are bound from the server.

Generate data- Html Attribute Using IClientModelIValidator:

To follow this approach let's create a new custom validation attributes(here creating new custom validation attribute for code displaying purpose, if you want you can override previous custom validation attribute with this approach)
Attributes/TextMatch2Attribute.cs:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using MvcValidation.App.Models;

namespace MvcValidation.App.Attribute
{
    public class TextMatch2Attribute : ValidationAttribute, IClientModelValidator
    {
        public string ExpectedText { get; set; }
        public TextMatch2Attribute(string expectedText)
        {
            ExpectedText = expectedText;
        }

        public string GetErrorMessage() => $"Enter value should always be {ExpectedText}";
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            MergeAttribute(context.Attributes, "data-val-textMatch", GetErrorMessage());
            MergeAttribute(context.Attributes, "data-val-textMatch-expectedText", ExpectedText);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var person = (Person)validationContext.ObjectInstance;
            if (string.IsNullOrEmpty(person.Name) || person.Name.ToLower() != ExpectedText.ToLower())
            {
                return new ValidationResult(GetErrorMessage());
            }
            return ValidationResult.Success;
        }

        private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }

            attributes.Add(key, value);
            return true;
        }
    }
}
Here custom attributes extend  ValidationAttribute class to implement custom validation logic and it also implementing IClientModelValidator which helps to bind data- attributes to the Html.

Update Model class to use this new custom validation attribute as follows
Models/Person.cs:
[TextMatch2("Iron Man")]
public string Name { get; set; }
Now run application and inspect Html elements, we can see data- attributes render to the Html elements.

Dynamic Form Validation Using jQuery Unobtrusive Validation:

Some times we may need to load a form dynamically load the form, for those forms validation will not work like forms loaded on-page. But we have the option to add validation to forms loaded through AJAX call by parsing them by jQuery Unobtrusive Validation.

Add a new action method in PersonController.cs as below
PersonController.cs:
[HttpGet]
[Route("test-page")]
public IActionResult TestPage()
{
 return View("Test");
}
Views/Person/Test.cshml:
<div>
    <div class="row">
        <div class="col col-sm-12">
            <button type="button" class="btn btn-primary" id="loadform">Load Form And Add Dynamic Validations</button>
        </div>
    </div>
    <div class="row" style="margin-top:10px">
        <div class="col col-sm-12">
            <div id="form-container">

            </div>
        </div>
    </div>
    
</div>
@section Scripts{

    @await Html.PartialAsync("/Views/Shared/_ValidationScriptsPartial.cshtml")
    <script src="~/js/customValidation.js"></script>
    <script src="~/js/dynamicForm.js"></script>
}
Here on this page, we have a button on clicking it loads form by AJAX Call and then it will be rendered inside the div with an id of 'form-container'.
wwwRoot/js/dynamicForm.js:
$("#loadform").click(function () {
    $("#form-container").html('');
    $.get({
        url: "https://localhost:44397/person/get-dynamic-form",
        dataType: "html",
        error: function (jqXHR, textStatus, errorThrown) {
            alert(textStatus + ": Couldn't add form. " + errorThrown);
        },
        success: function (newFormHTML) {
            var container = document.getElementById("form-container");
            container.insertAdjacentHTML("beforeend", newFormHTML);
            var forms = container.getElementsByTagName("form");
            var newForm = forms[forms.length - 1];
            $.validator.unobtrusive.parse(newForm);
        }
    })
})
Here we are calling an MVC action method that delivers partial view which contains a form that will be returning as a response. '$.validator.unobtrusive.parse('yourform')' this method helps to parse the form Html and activate the client-side validations.

Now add a new action method in PersonController.cs that delivers partial view
PersonController.cs:
[HttpGet]
[Route("get-dynamic-form")]
public IActionResult DynamicForm()
{
 return PartialView("DynamicPartilForm");
}
Views/Person/DynamicPartilForm.cshtml:
<div>
    <form >
       
        <div class="form-group row">
                <label  class="col-sm-2 col-form-label">Name</label>
                <div class="col-sm-10">
                    <input 
                           id="Name",
                           name="Name"
                           data-val="true"
                           data-val-textMatch="Enter value should always be Naveen"
                           data-val-textMatch-expectedText="Naveen"
                           type="text" class="form-control" />
                    <span class="text-danger field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
                </div>

            </div>
        <div class="form-group row">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>
Now run the application and navigate to "https://localhost:44397/person/test-page" which show as below
Now click on the button we can see dynamic form get rendered at the bottom of the button as below
Now submit the form with an empty input field, we can observe client-side validations get fired

Summary:

We have covered server-side validation and client-side validation and then discussed custom validation attributes creation. we have manually written the logic for custom validation at the client-side with the help of the jQuery Unobtrusive Validation library. We learned about validation sync between server-side and client-side using data- attributes. Finally we hands-on dynamic forms client-side validations.

Refer:


Comments


  1. A very good very detailed blog, thanks to this article, I have understood the logic of validation using whatever server or client side, content to clarify us subtle congratulations thank you again

    ReplyDelete

Post a Comment

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually