ASP.NET Core MVC Model Validation

Debasis Saha  Print 
24 Aug 2018
 
Intermediate
258

When we developed any type of application such as web-based or desktop based, in both the application one is the key part of development is Data Validation or Form Validation. These validations always ensure us that user fills the correct form of data into the application so that we can process that data and save for future use. Actually, normally users always fill the form with necessary information and submit the form. But, sometimes the user make some mistakes. In this case, form validation is required to ensure that the user always provides the required information in the proper format which is required for the successful submission of the form. In this article, we will discuss this different types of form validations.

When we visit any popular website for the registration purpose, we notice that that site gives us some error message or warning message when we did not put properly formatted data in the form's controls. Normally, we receive the message as below –

  1. The field value is required. We can’t leave the field blank.

  2. Please enter your data in correct format in case of phone number, date of birth etc.

  3. Please provide a valid email address.

  4. Your password does not match the format like uppercase, one symbol and one number.

This type of message known as form validations. Actually, when a user fills the data in the forms, web applications validate those data either it is correct or not. If it is correct, then application send those data to the server for saving into the database. If it not in correct format, then it throws error messages providing information about what corrections need to done by the user. So, we can implement the form validation in different ways. These validations are important for any developers due to the below reasons –

  1. We always want to receive the correct the data in correct format from the user.

  2. We want to protect the user data by forcing user to provide some confidential information in a specified format.

  3. Also, by the help of form validations, we can protect ourselves from malicious uses of our applications.

VALIDATION TYPES

Forcing user to provide properly formatted and necessary information for any types of forms is the main objectives of the form validations. Normally, we can perform form validation in two ways – either implement in the server-side code i.e. Server-Side Validation or implement these in the client-side i.e. Client-Side Validations. In the below section, we discuss both the validation types.

SERVER-SIDE VALIDATION

In case of Server-side validation, information filled by the users are send to the server and then validate that information using the server-side language i.e. in the Asp.Net Core. In this process, if the data not validated, then a response along with proper error message is sent back to the client where these messages are shown to the user so that those wrong data can be rectified. This type of validation is always secure because if the user disabled the scripting language in the browser then also it will work. At the same time, it can’t be bypassed by the user very easily. But the one problematic concern is that user not able know what mistakes have been done until the user completes the data entry and submit the data. Since these processes always communicate with the server, that’s why it is a little bit slow process for the output or error message.

In Asp.Net Core, the best way to perform the server-side validation is using Model Validation. Likely, Microsoft provides us with the abstract validation layer as validation attributes which contains validation code. Therefore, these approaches always reduce the amount of code writing for us. Validation attribute is one of the ways to implement or configure model validations in the model class property. These validations can be works like constraint such as assign maximum length or required fields. There are also other validation types which can implement some common business rules on data like – Email Address, Phone, Range etc. Validation attribute always enforces some logical business rule in a simple and easy to use way. Below is an Employee Model for an application in which Validation attributes like required, length has been implemented.

public class Employee
{
public int Id { get; set; }

[Required]
[StringLength(100)]
public string EmployeeName { get; set; }

[Required]
[DataType(DataType.Date)]
public DateTime JoinDate { get; set; }

[Required]
[StringLength(100)]
public string Designation { get; set; }

[Range(0, 999.99)]
public decimal Salary { get; set; }

[Required]
public Gender Gender { get; set; }

public string Address { get; set; }
}

From the above model class, it is clearly shown that we just need to add the related rule in the model class properties to enforce user to provide proper data. In the below table, there are some popular inbuild available validation attributes in the Asp.Net Core –

Required
This validation attributes makes any property as required or mandatory.
StringLength
This validation attributes validate any string property along with itslength
Compare
This validation attribute basically compares the two property values in a model match
EmailAddress
This validation attribute validates the email address format
Phone
This validation attribute validates the phone no format
CreditCard
This attribute validates a credit card format
Range
This validation attributes any property to check it is exist within the given range or not.
Url
This validation attributes validates the property contains an URL format or not
RegularExpression
This validation attributes normally match the data which specified the regular expression format.

Asp.Net Core provide supports against all the validation attributes which are inherited from the ValidationAttribute class. Also, we can create custom server-side validation attribute by implementing the interface named IValidationObjects. In Asp.Net Core, Model state always return validation errors in a normal HTML format in the interface. This will continue the validation process against the form field until the total error number reaches into its maximum limits (200 is by default). But we can configure this maximum error number in the ConfigureServices() in the Startup.cs class.

services.AddMvc(options => options.MaxModelValidationErrors = 50);

CLIENT-SIDE VALIDATION

Server-Side validation is the most successful and secure validation process. But sometime, we need to implement client-side validation for the better user experience. Normally, this type of validations done by the scripting languages in the client side. By using this type of validation, we can implement much more responsive and visually rich validation on the users input data at the client side. The most best things of this types of validations is that form submit method is not executed in this case if validation fails. Means, if we implement client-side validation in our application, then server-side method or process will be invoked only when client-side validation has been passed successfully. Otherwise, it will not invoke the server-side code so there is not load in the server-side. So, that’s why Client-Side validation always performs faster execution of error and it increase the performance of the applications.

But the main disadvantages of this types of validation is that it is totally depends on the JavaScript languages. So, if user disabled the JavaScript in the browser, then the validation process can be bypassed and server-side method can be invoked with the wrong data. And, also if we do not implement the same client-side validation in the server-side also, then there is a high probability that system can accept the wrong or incorrect data. For this reason, it is always better to implement the same validation rule or method in the both side i.e. Server-side and Client-Side.

So, for implement the Client-side validation, we need to add the proper JavaScript script reference in the UI for this purpose as below –

 <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
 <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
 <script 
 src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.mi
 n.js"></script>

In the above script reference, jQuery Unobtrusive Validation is one the custom front-end library provided by the Microsoft on the based of most popular and well known scripting library JQuery validate plugin. These front-end is totally responsible for the implementing the same validation logic in the both side of the application. We can generate any type of custom data attributes for both server and client side with help of Asp.Net Core. For custom data attribute, JQuery Unobtrusive library simply transfer the server side validation logic to the client side. We can display the validation error message in the client side with the help of related Tag Helpers as shown below –

<div class="form-group">
<label asp-for="JoineDate" class="col-md-4 control-label"></label>
<div class="col-md-10">
<input asp-for=" JoineDate" class="form-control" />
<span asp-validation-for="JoineDate" class="text-danger"></span>
</div>
</div>

In the above code sample, data attribute validation is used only for the JoineDate Property. If you does not fill this field value, then data-val-required attribute always contains an error message which we provide the server-side. In this way, jQuery Unobtrusive library pass the validation to the client-side as required, which will be displayed in the span tag or an alert window.

<form action="/Employee/Create" method="post">
<div class="form-horizontal">
<h4> Employee Information</h4>
<div class="text-danger"></div>
<div class="form-group">
<label class="col-md-2 control-label" for="JoineDate"> JoineDate </label>
<div class="col-md-10">
<input class="form-control" type="datetime"
data-val="true" data-val-required="The Date of Join field is required."
id="JoineDate " name="JoineDate" value="" />
<span class="text-danger field-validation-valid"
data-valmsg-for="JoineDate" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</form>

CUSTOM SERVER-SIDE VALIDATIONS AND CLIENT-SIDE VALIDATIONS

So, both Server-side and Client-Side validation attributes works perfectly for the most of the cases and also fulfill the requirement related the validation required. But, still there some situation, when we need to specify some specify custom validation related the business for that model class. In this case, custom validation is the one of the best process to perform the validations. We can implement the custom validation either in the both side i.e. Server-Side and Client-Side very easily. These custom validations might not be same as the validation attributes required in the server-side. For doing these, we need to inherit ValidationAttribute in our class and then we need to override the method called IsValid(). It is always accepts two parameters – the first parameter is an object type called value and the second one is the object of ValidationContext on the requirement also implemented in validationContext.

In the below example, we will demonstrate the default custom validation format for the service side.

public class EmployeeAttribute : ValidationAttribute, IClientModelValidator
{
private int _year;
public EmployeeAttribute(int Year)
{
_year = Year;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Employee employee = (Movie)validationContext.ObjectInstance;
if (employee.Gender == Gender.Male && employee.ReleaseDate.Year> _year)
{
return new ValidationResult(GetErrorMessage());
}
return ValidationResult.Success;
}

In the above example, employee variable act as Employee objects, which generate the IsValid() of the EmployeeAttribute class generate the rule as per the policy. ValidationResult.Success code has been return after the execution of validation. Similarly, an error result as an ValidationResult has been return in case of validation fails.

private string GetErrorMessage()
{
return $"Employee Must the have the Joining Date";
}

Also, the same validation rule can be implemented by the help of validate() by using the IValidatableObject interface. Custom validation attributes main objective is to perform checking against the individual properties of the model class. In this case, IValidatableObject can be implemented class-level validations.

public IEnumerable<ValidationResult>ValidateEmployee(ValidationContext validationContext)
{
if (Gender == Employee.Male && JoinDate.Year > _year)
{
yield return new ValidationResult(
$" Employee Must the have the Joining Date.",
new[] { "ReleaseDate" });
}
}

So, we can also add the custom validation in the Client-Side. For that we need to use the jQuery Unobtrusive validation process to pass the server-side validation to the client-side.

 var form = document.getElementById("my-form");
form.insertAdjacentHTML("beforeend", newInputHTML);
$(form).removeData("validator").removeData("unobtrusiveValidation"); 
$.validator.unobtrusive.parse(form);

We may also create client side custom validation logic for our custom attribute and then unobtrusive validation create an jQuery adapter which will execute the custom validation logic in the client machine for the part of the automatic validation process. The first step for this to add the data attributes by using IClientModelValidator interface.

public void AddEmployeeValidation(ClientModelValidationContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
MergeAttribute(context.Attributes, "data-employee", "true");
MergeAttribute(context.Attributes, "data-employee", GetErrorMessage());
var age = _year.ToString(CultureInfo.InvariantCulture);
MergeAttribute(context.Attributes, "data- employee -year", age);
}

So, these are the custom attributes which can be used in the HTML part when we use that. Now the sample HTML which can implement the above custom validation attributes as

<input class="form-control" type="datetime"
data-val="true"
data-val-employee ="Employee Date of Birth Must be Before year 2000."
data-val-employee -year="2000"
data-val-required="The Joining Date field is required."
id="JoinDate" name=" JoinDate " value="" />
SUMMERY

So, in this article, we discuss about the concept of Form Validation in ASP.Net Core including the Server-Side Validations and Client-Side Validations. Also, we discuss about how to create custom validation in server-side and client-side.

Hands-on Learning
Free Interview Books
 
+