Razor form validation in Asp.net Core MVC, Model Validation in asp.net core Razor, Asp.net Core validation Example

Asp.net Core form validation Example

Form validation is one of the most useful features in any web application, here we learn Asp.net Core Validation Tutorial for beginners step by step.

Asp.net Core razor form validation

When you accept data input from user then save the data in database, you must ensure that all incoming values that user has entered, are matching with data type, length specified in database, otherwise that will produce error and won’t be able to save the data in database.

So, you have to validate before processing data.

There are differ ways you can validate data in Asp.net Razor Form
Razor page framework are built on MVC Framework, so it supports following input validation framework.

  • Validation using DataAnnotation Attributes
  • Vlidation using Tag Helpers
  • jQuery Unobtrusive Validation
  • Server Side Validation Technique

Model Validation using DataAnnotation Attributes

Validation using DataAnnotation Attributes in Asp.Net Core works in the same way we used to perform validation in earlier Asp.net MVC.

All validation classes are inherited from ValidationAttribute, You need to use DataAnnotations class reference by adding System.ComponentModel.DataAnnotations Namespace

Validation Attributes in Asp.net Core

  • Required

    Indicates that the value must be provided for this field, else display error message

  • Range

    Specify the minimum and maximum values of a range, so user must provide a value within that range

  • Compare

    Compare the value of two fields, or with a fixed specified value

  • StringLength

    Sets the maximum number of string characters allowed

  • MaxLength

    Sets the maximum length, number of characters can be accepted

  • MinLength

    Sets the minimum length, number of characters can be accepted

  • RegularExpression

    Checks if the value matching against the specified regular expression

  • Remote

    It helps enabling client-side validation against a server-side code, like checking database to see if a partial email id is already in use

Client side validation in Razor Asp.net Core

In form you also can provide client side validation support using jQuery.
Here we design a simple form to show how to display

<form method="post">
<input asp-for="FullName" />
<span asp-validation-for="FullName"></span>
<input asp-for="Email" />
<span asp-validation-for="Email"></span>
    <input asp-for="ContactNumbers" />
    <span asp-validation-for="ContactNumbers"></span>
    <input type="submit" value="Submit" />

If you check how the html look like after rendering, notice data-val="true", if set data-val="false" then validation won't happen

<form method="post">
Name:<input type="text" data-val="true" data-val-length="5-60 character" data-val-length-max="60" data-val-length-min="5" data-val-required="Full Name Required" id="FullName" name="FullName" value="" />
<span class="field-validation-valid" data-valmsg-for="FullName" data-valmsg-replace="true"></span>
Email: <input type="email" data-val="true" data-val-email="Invalid email" data-val-required="Email required" id="Email" name="Email" value="" />
<span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>
Mobile: <input type="text" data-val="true" data-val-length="10-14 character" data-val-length-max="14" data-val-length-min="10" data-val-required="Contact Numbers Required" id="ContactNumbers" name="ContactNumbers" value="" />

Make sure you have added following jquery files as reference in your page

@section scripts
    <script src="~/lib/jquery.js"></script>
    <script src="~/lib/jquery.validate.js"></script>
    <script src="~/lib/jquery.validate.unobtrusive.js"></script>

Asp.net Core Model Validation Example

Server side validation: Sometimes it’s necessary to implement server side validation, because we cannot depend on client side validation completely, there are ways to disable client side script, sometimes they are not supported by different version of different browsers, sometimes bugs can cause problem, so in framework there is also an easy way to check server side validation.

public class ContactModel : PageModel
        [Required(ErrorMessage = "Full Name Required")]
        [StringLength(60, ErrorMessage = "5-60 character", MinimumLength = 5)]
        public string FullName { get; set; }
        [Required(ErrorMessage = "Contact Numbers Required")]
        [StringLength(14, ErrorMessage = "10-14 character", MinimumLength = 10)]
        public string ContactNumbers { get; set; }
        [EmailAddress(ErrorMessage = "Invalid email")]
        [Required(ErrorMessage = "Email required")]
        public string Email { get; set; } 
        public void OnGet()
            Message = "Your application description page.";
        public void OnPost()
            string _email = Request.Form["Email"];

In every PageModel validation error is added to ModelStateDictionary, and you can access the dictionary result using ModelState of PageModel class.

ModelState has a property called IsValid, which indicates if validation check is successful, if not the IsValid property become false.

Here is how you can check the validation at server side

public IActionResult  OnPost()
    if (ModelState.IsValid)
        // add data in database 
           var fullName = FullName;
            var contactNumbers =  ContactNumbers;
            var email =  Email;
          // then redirect to success page
          // redirect to validation page

Asp.net Core Remote Validation Example

Remote validation is basically validating data with database or any other external web services while user entering data in text box, making an ajax call to server side code to check if the input is valid or else display the error message immediately.

Here I have written an example of Remote Validation Implementation in Asp.net Core

Validation in Razor Pages
ASP.NET MVC Interview Questions Answers
Hire Asp.net Developer
Asp.Net Core C# Examples | Join Asp.Net MVC Course