ASP NET core remote validation



Remote validation in ASP.NET Core with an example.

What is remote validation in ASP.NET Core

Healthy diet is very important for both body and mind. We want to inspire you to cook and eat healthy. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking.
https://www.youtube.com/channel/UC7sEwIXM_YfAMyonQCrGfWA/?sub_confirmation=1

Text version of the video
https://csharp-video-tutorials.blogspot.com/2019/06/aspnet-core-remote-validation.html

Slides
https://csharp-video-tutorials.blogspot.com/2019/06/aspnet-core-remote-validation-slides.html

ASP.NET Core Text Articles & Slides
https://csharp-video-tutorials.blogspot.com/2019/01/aspnet-core-tutorial-for-beginners.html

ASP.NET Core Tutorial
https://www.youtube.com/playlist?list=PL6n9fhu94yhVkdrusLaQsfERmL_Jh4XmU

Angular, JavaScript, jQuery, Dot Net & SQL Playlists
https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd

Remote validation allows a controller action method to be called using client side script. This is very useful when you want to call a server side method without a full page post back.

Remote validation example

Checking, if the provided email is already taken by another user can only be done on the server. The following IsEmailInUse() controller action method checks if the provided email is in use.

[AcceptVerbs(“Get”, “Post”)]
[AllowAnonymous]
public async Task[IActionResult] IsEmailInUse(string email)
{
var user = await userManager.FindByEmailAsync(email);

if (user == null)
{
return Json(true);
}
else
{
return Json($”Email {email} is already in use.”);
}
}

This method should respond to both HTTP GET and POST. This is the reason we specified both the HTTP verbs (Get and Post) using [AcceptVerbs] attribute.
ASP.NET Core MVC uses jQuery remote() method which in turn issues an AJAX call to invoke the server side method.
The jQuery remote() method expects a JSON response, this is the reason we are returing JSON response from the server-side method (IsEmailInUse)

ASP.NET core remote attribute

The following is the model class for the User Registration View. Notice, we have decorated the Email property with the [Remote] attribute pointing it to the action method that should be invoked when the email value changes.

public class RegisterViewModel
{
[Required]
[EmailAddress]
[Remote(action: “IsEmailInUse”, controller: “Account”)]
public string Email { get; set; }

// Other properties
}

ASP.NET core remote validation not working

The following 3 client-side libararies are required in the order specified for the remote validation to work. If any of them are missing or not loaded in the order specified, remote validation will not work.

[script src=”~/lib/jquery/jquery.js”][/script]
[script src=”~/lib/jquery-validate/jquery.validate.js”][/script]
[script src=”~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js”][/script]

Comments are closed.