Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7521003
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T02:09:48+00:00 2026-05-30T02:09:48+00:00

I just created a sample MVC3 application to learn validation. It is using DataAnnotations.

  • 0

I just created a sample MVC3 application to learn validation. It is using DataAnnotations. I have created a custom ValidationAttribute named CustomStartLetterMatch. It is implementing “System.Web.Mvc.IClientValidatable”. I have corresponding client-side code written with unobtrusive jQuery. This is working as expected.

About the custom validator: It compares the first name input and last name input. It throws error if first character of both of them are not same.

As I said, the application is working fine. But when I looked at the rule.ValidationType = "greaterdate"; I got confused. I wanted to change it to something else like “anotherDefaultType”. When I am changing it, it fails with jQuery error.

  1. What is the reason for this?
  2. What are the available ValidationTypes?
  3. What is the suggested approach to change the ValidationType in this scenari

CODE:

using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace MyValidationTEST
{
    public class Person
    {
    [Required(ErrorMessage = "First name required")]
    public string FirstName { get; set; }

    [CustomStartLetterMatch("FirstName")]
    [StringLength(5,ErrorMessage = "Must be under 5 characters")]
    public string LastName { get; set; }

    [Range(18,50,ErrorMessage="Must be between 18 and 50")]
    public int Age { get; set; }

}



public sealed class CustomStartLetterMatch : ValidationAttribute, System.Web.Mvc.IClientValidatable 
{

    private const string _defaultErrorMessage = " First letter of '{0}' must be same as first letetr of '{1}'";
    private string _basePropertyName;

    public CustomStartLetterMatch(string basePropertyName)
        : base(_defaultErrorMessage)
    {
        _basePropertyName = basePropertyName;
    }


    //Override FormatErrorMessage Method
    public override string FormatErrorMessage(string name)
    {
        return string.Format(_defaultErrorMessage, name, _basePropertyName);
    }


    //Override IsValid
    protected override ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
    {
        //Get PropertyInfo Object
        var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
        var baseValue = (string)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
        var currentValue = (string)value;


        string firstLetterBaseValue = baseValue.Substring(0, 1);
        string firstLetterCurrentValue = currentValue.Substring(0, 1);

        //Comparision
        if (!string.Equals(firstLetterBaseValue, firstLetterCurrentValue))
        {
            var message = FormatErrorMessage(validationContext.DisplayName);
            return new ValidationResult(message);
        }

        //Default return - This means there were no validation error
        return null;
    }


    public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, System.Web.Mvc.ControllerContext context)
    {
        var rule = new System.Web.Mvc.ModelClientValidationRule();
        rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
        rule.ValidationParameters.Add("other", _basePropertyName);
        rule.ValidationType = "greaterdate";
        yield return rule;
    }



}

}

VIEW

@model MyValidationTEST.Person

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>

<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript">  </script>

@*UnObtrusive*@
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>



<script type="text/javascript">

/*Register adapter - addSingleVal*/
jQuery.validator.unobtrusive.adapters.addSingleVal("greaterdate", "other");


/*Validation type names in unobtrusive client validation rules must consist of only lowercase letters*/

/*Add Method*/
jQuery.validator.addMethod("greaterdate",
                                    function (val, element, other) 
                                    {

                                        var modelPrefix = element.name.substr(0, element.name.lastIndexOf(".") + 1)
                                        var otherVal = $("[name=" + modelPrefix + other + "]").val();

                                        if (val && otherVal) 
                                        {
                                            var lastNameFirstLetter = val.substr(0, 1);
                                            var firstNameFirstLetter = otherVal.substr(0, 1);

                                            if (lastNameFirstLetter != firstNameFirstLetter) 
                                            {
                                                return false;
                                            }
                                        }
                                        return true;
                                    });


</script>


@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Person</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Age)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Age)
        @Html.ValidationMessageFor(model => model.Age)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

CONTROLLER:

using System.Web.Mvc;
namespace MyValidationTEST.Controllers
{
public class RelativesController : Controller
{

    // GET: /Relatives/
    public ActionResult Index()
    {
        return View();
    }



    // GET: /Relatives/Create
    public ActionResult Create()
    {
        Person person = new Person();
        return View(person);
    }


    // POST: /Relatives/Create
    [HttpPost]
    public ActionResult Create(Person relativeToAdd)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("Index");
        }
        return View(relativeToAdd);
    }

    }

 }

READING:

ASP.NET MVC3 – Custom validation attribute -> Client-side broken

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T02:09:49+00:00Added an answer on May 30, 2026 at 2:09 am

    I wanted to change it to something else like “anotherDefaultType”

    You can use only lowercase letters for the ValidationType property:

    rule.ValidationType = "anotherdefaulttype";
    

    and then adapt your client script to reflect this modification:

    jQuery.validator.unobtrusive.adapters.addSingleVal("anotherdefaulttype", "other");
    jQuery.validator.addMethod("anotherdefaulttype", function (val, element, other) {
        ...
    });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have created a sample web application in Visual Studio 2010. It stores Membership
I have created a sample application suing Application cache, My some files are located
I created a simple .NET windows application in Visual Studio 2005 and on just
Just created a WSS site with a some custom web-parts. But I get an
I created one sample phone app just dial a entered number like Intent callIntent
i recently created a sample application, wherein i implemented the events and delegates, when
I'm playing around with using ASP.NET MVC3 and have a very simple site that
I'm just starting my first MVC3 application, and I'm not sure how to unit-test
I've created a sample project to simplify my problem. I have this simple handler:
Suppose I am creating a application using the sample Northwind database using asp.net mvc

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.