using System.Text.RegularExpressions;
public static class PhoneValidator
{
// ✅国内電話番号(先頭0 +ハイフン任意)
//例: 03-1234-5678 / 090-1234-5678 / 0312345678
private static readonly Regex DomesticPhoneRegex = new Regex(
@"^0\d{1,4}-?\d{1,4}-?\d{4}$",
RegexOptions.Compiled);
// ✅国際対応版(+記号+国番号+国内番号)
//例: +81-3-1234-5678 / 03-1234-5678 / +1 555 123 4567
private static readonly Regex InternationalPhoneRegex = new Regex(
@"^(\+?\d{1,4}[-\s]?)?\d{2,5}[-\s]?\d{2,5}[-\s]?\d{2,5}$",
RegexOptions.Compiled);
public static bool IsValidDomestic(string phone)
{
if (string.IsNullOrWhiteSpace(phone))return false;
return DomesticPhoneRegex.IsMatch(phone);
}
public static bool IsValidInternational(string phone)
{
if (string.IsNullOrWhiteSpace(phone))return false;
return InternationalPhoneRegex.IsMatch(phone);
}
}
//使い方
class Program
{
static void Main()
{
//国内
Console.WriteLine(PhoneValidator.IsValidDomestic("03-1234-5678")); // True
Console.WriteLine(PhoneValidator.IsValidDomestic("0312345678")); // True
Console.WriteLine(PhoneValidator.IsValidDomestic("090-1234-5678")); // True
Console.WriteLine(PhoneValidator.IsValidDomestic("+81-3-1234-5678")); // False
//国際
Console.WriteLine(PhoneValidator.IsValidInternational("+81-3-1234-5678")); // True
Console.WriteLine(PhoneValidator.IsValidInternational("+1 555 123 4567")); // True
}
}
▸ 実行ボタンで結果を表示
Source収録記事
この snippet は記事の「パターン2:電話番号検証—国内+国際対応」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。
同じ記事から
5 件using System.Text.RegularExpressions; public static class EmailValidator {
▶ 実行可
パターン1:メールアドレス検証—簡易版が現実解
#8e620c411684
using System.Text.RegularExpressions; public static class PostalCodeValidator {
▶ 実行可
パターン3:郵便番号検証— 7桁ハイフン形式
#da3fce3a8fab
using System.Text.RegularExpressions; public static class CharTypeValidator {
▶ 実行可
パターン4:全角半角判定— Unicode範囲
#50a671243a77
using System; using System.Text.RegularExpressions; public static class FormatValidator
▶ 実行可
パターン5:数値・日付フォーマット検証
#5f14a216eab8
using System.Diagnostics; using System.Text.RegularExpressions; public static class RegexPerformanceComparison
▶ 実行可
パターン6: RegexOptions.Compiledでパフォーマンス改善
#228fa557c142
