Я только что создал образец приложения MVC3, чтобы изучить валидацию. Он использует DataAnnotations. Я создал настраиваемый атрибут ValidationAttribute с именем CustomStartLetterMatch. Он реализует «System.Web.Mvc.IClientValidatable». У меня есть соответствующий клиентский код, написанный ненавязчивым jQuery. Это работает, как ожидалось.
О настраиваемом валидаторе: он сравнивает введенные имя и фамилию. Выдает ошибку, если первые символы обоих из них не совпадают.
Как я уже сказал, приложение работает нормально. Но когда я посмотрел на правило rule.ValidationType = "moredate";
, я запутался. Я хотел изменить его на что-то другое, например, «anotherDefaultType». Когда я его меняю, происходит сбой с ошибкой jQuery.
КОД:
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 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;
}
}
}
ПРОСМОТР
@model MyValidationTEST.Person
@{
ViewBag.Title = "Create";
}
Create
@*UnObtrusive*@
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
}
@Html.ActionLink("Back to List", "Index")
КОНТРОЛЛЕР:
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);
}
}
}
ЧТЕНИЕ:
ASP.NET MVC3 - Пользовательский атрибут проверки -> На стороне клиента не работает