.SHARP{C#DERS}

.net development, server management, and related topics

ASP.Net MVC Remote Validator

This is an old post from my now defunct personal blog


Sometimes regex validators are not enough. I have a case where I want to make sure an email address exists in a database when a person is filling out a form. To do this you can use a remote validator which performs an AJAX call to an action for a result.

First in your model add the remote attribute to the property you want validated. Code is shortened for clarity

Imports System.ComponentModel.DataAnnotations

Namespace MyApp.Models
    Public Class MyForms      
         'first parameter is the MVC action, the second is the controller name
        <Remote("IsValidEmail", "request")>
        <Display(Name:="Requestor Email Address")>
    End Class
End Namespace

Then in the controller add a an action like this:

Function IsValidEmail(RequestorEmail As String) As JsonResult
            If UtilityFunctions.IsValidEmail(RequestorEmail) Then
                'if the user exists in my database
                If UtilityFunctions.IsEmailAddressInSystem(RequestorEmail) Then
                    Return Json(True, JsonRequestBehavior.AllowGet)
                Else
                    Return Json("Email address not found in system", JsonRequestBehavior.AllowGet)
                End If
            Else
                Return Json("Invalid Email Address", JsonRequestBehavior.AllowGet)
            End If
        End Function

Finally in the view add the validator - Be sure to include jquery and the validate, ajax, and unobtrusive javascripts.

@Html.EditorFor(Function(model) model.RequestorEmail)
@Html.ValidationMessageFor(Function(model) model.RequestorEmail)
Comments are closed