I noticed that when creating a custom validation attribute, my validation only works after writing annotations of my own MVC data. Can it work "simultaneously"?
To show what I mean, pretend that I have this form:
FirstName: <FirstName Textbox> LastName: <LastName TextBox> Zip: <Zip TextBox>
So, I have an annotation [Required] for all 3, but also, for the Zip property, I have a custom attribute. If the user does NOT enter a first or last name, but enters an invalid Zip (which should confirm my attribute), all three should have an error message, but no. There is only error firstName and lastName.
This is the code:
Person.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; // My validator using MvcApplication3.Extensions.Validation; namespace MvcApplication3.Models { public class Person { [Required(ErrorMessage="Field required!")] public string firstName{get;set;} [Required(ErrorMessage="Field required!")] public string lastName { get; set; } [Zip(ErrorMessage="You gotta put in a valid zip code")] [Required(ErrorMessage="Field required!")] public string zipCode { get; set; } } }
Controller:
[HttpPost] public ActionResult Index(FormCollection form, Person person) { return View(person); }
View:
@model MvcApplication3.Models.Person @{ ViewBag.Title = "Person"; Layout = "~/Views/Shared/_Layout.cshtml"; } <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> <h2> Testing Form: @Model.firstName </h2> <hr /> @{Html.EnableClientValidation();} @using (Html.BeginForm()) { @Html.LabelFor(model => model.firstName) @Html.TextBoxFor(model => model.firstName) @Html.ValidationMessageFor(model=>model.firstName) <br /><br /> @Html.LabelFor(model => model.lastName) @Html.TextBoxFor(model => model.lastName) @Html.ValidationMessageFor(model=>model.lastName) <br /><br /> @Html.LabelFor(model => model.zipCode) @Html.TextBoxFor(model => model.zipCode) @Html.ValidationMessageFor(model=>model.zipCode) <br /><br /> <input type="submit" value="Submit" /> }
Zip Validator (Zip.cs):
public class ZipAttribute : ValidationAttribute { public override bool IsValid(object value) { bool foundMatch = false; try { foundMatch = Regex.IsMatch(value.ToString(), "\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z"); } catch (ArgumentException ex) {
In addition, I know that I can do this with a Regexp data annotation, but in the future I will look for my own validators.
Thanks!
source share