動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

パターン5:数値・日付フォーマット検証

出典: C# 正規表現の業務系基本 — メール / 電話 / 郵便番号 / 全角半角の入力検証5パターンパターン5:数値・日付フォーマット検証

パターン5:数値・日付フォーマット検証 (csharp)#5f14a216eab8
using System;
using System.Text.RegularExpressions;
 
public static class FormatValidator
{
    // ✅整数(正負・桁数指定なし)
    private static readonly Regex IntegerRegex = new Regex(
        @"^-?\d+$",
        RegexOptions.Compiled);
 
    // ✅小数(正負・小数点任意)
    private static readonly Regex DecimalRegex = new Regex(
        @"^-?\d+(\.\d+)?$",
        RegexOptions.Compiled);
 
    // ✅日付YYYY/MM/DD
    private static readonly Regex DateRegex = new Regex(
        @"^\d{4}/\d{2}/\d{2}$",
        RegexOptions.Compiled);
 
    public static bool IsInteger(string input)
    {
        return !string.IsNullOrWhiteSpace(input)&& IntegerRegex.IsMatch(input);
    }
 
    public static bool IsDecimal(string input)
    {
        return !string.IsNullOrWhiteSpace(input)&& DecimalRegex.IsMatch(input);
    }
 
    //日付はRegex + DateTime.TryParseの二段検証
    public static bool IsValidDate(string input)
    {
        if (string.IsNullOrWhiteSpace(input))return false;
        if (!DateRegex.IsMatch(input))return false;
 
        //フォーマット通過後、実在日付か検証(2026/02/30を弾く)
        return DateTime.TryParseExact(input, "yyyy/MM/dd",
            null, System.Globalization.DateTimeStyles.None, out _);
    }
}
 
//使い方
class Program
{
    static void Main()
    {
        Console.WriteLine(FormatValidator.IsInteger("123"));      // True
        Console.WriteLine(FormatValidator.IsInteger("-456"));     // True
        Console.WriteLine(FormatValidator.IsInteger("12.3"));     // False
 
        Console.WriteLine(FormatValidator.IsDecimal("3.14"));     // True
        Console.WriteLine(FormatValidator.IsDecimal("-2.5"));     // True
 
        Console.WriteLine(FormatValidator.IsValidDate("2026/05/15"));  // True
        Console.WriteLine(FormatValidator.IsValidDate("2026/02/30"));  // False(実在しない)
    }
}
▸ 実行ボタンで結果を表示
  • id: #5f14a216eab8
  • lines: 58
  • extracted: 2026-06-10
  • captured: 2026-06-04

Source収録記事

この snippet は記事の「パターン5:数値・日付フォーマット検証」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

5
図鑑トップ