Help us understand the problem. What is going on with this article?

ASP.NET MVCで検証属性を自作する

More than 1 year has passed since last update.

ASP.NET MVCが提供している検証属性だけじゃ足りない!!!

そういう場合は自作する必要があります。

つくりかた

ValidationAttributeクラスを継承したクラスを作成し、IsValidメソッドをオーバーライドします。

クラス名は「HogeAttribute」のように末尾にAttributeを付与してください。

using System;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace Sample.CustomValidationAttribute
{
    /// <summary>
    /// 入力値が「yyyy/MM/dd」形式であるかを検証します。
    /// </summary>
    public class DateAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            if (value != null)
            {
                return Regex.IsMatch(value.ToString(), @"^(\d{4})/(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|3[01])$");
            }
            return false;
        }
    }
}

つかいかた

自作した検証は元々ある検証と同じように使用することが出来ます。

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Sample.CustomValidationAttribute;

namespace Sample.Dto
{
    public class PersonViewModel
    {
        [DisplayName("生年月日")]
        [Required]  // これはもともとあるやつ
        [Date]  // これ自作したやつ
        public string BirthDay { get; set; }
    }
}
maitake9116
インフラもフロントエンドもサーバサイドも検索エンジンもやるエンジニア. PowerShellでDB,GIS,WEBサーバーの構築を自動化した. TypeScript + ASP.NET MVCのアプリ基盤を構築. C#er. 全文検索(Elasticsearch, Solr)も構築経験あり. Hadoop, Pig でビッグデータ分析も可.
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした