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(実在しない)
}
}
▸ 実行ボタンで結果を表示
Source収録記事
この snippet は記事の「パターン5:数値・日付フォーマット検証」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
5 件using System.Text.RegularExpressions; public static class EmailValidator {
▶ 実行可
パターン1:メールアドレス検証—簡易版が現実解
#8e620c411684
using System.Text.RegularExpressions; public static class PhoneValidator {
▶ 実行可
パターン2:電話番号検証—国内+国際対応
#f2eebc57a171
using System.Text.RegularExpressions; public static class PostalCodeValidator {
▶ 実行可
パターン3:郵便番号検証— 7桁ハイフン形式
#da3fce3a8fab
using System.Text.RegularExpressions; public static class CharTypeValidator {
▶ 実行可
パターン4:全角半角判定— Unicode範囲
#50a671243a77
using System.Diagnostics; using System.Text.RegularExpressions; public static class RegexPerformanceComparison
▶ 実行可
パターン6: RegexOptions.Compiledでパフォーマンス改善
#228fa557c142
