How to Validate a Social Security Number using Regex in C# ?

Published on June 21, 2014 by abundantcode

Filed under C#

Last modified June 21, 2014

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 5 (1 votes)

This article have been viewed 4470 times

If you need to validate a social security number in C# , the regular expressions is one of the easy wat to do it .

Below is a sample code snippet demonstrating how to validate a social security number using regular expression .

The pattern for matching it is that SSN number contains nine digits grouped with hypen as option.

How to Validate a Social Security Number using Regex in C# ?

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace AbundantcodeConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
          //  How to Validate a Social Security Number using Regex in C# ?
           string SSNPattern = @"^\d{3}\-?\d{2}\-?\d{4}$";
           Regex regex = new Regex(SSNPattern);
           bool Matching = regex.IsMatch("111-22-45Q6");
           Console.WriteLine(Matching);
           Console.ReadLine();
        }     
    }
    
}

 

1

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Comment


x

You might be Interested in these Posts

How to Convert a Number to Bytes Array in C# ?

To Convert a number to a byte array , the developers can use the BitConverter.GetBytes method which ...

How to Print Leading Zeroes for a Number in C# ?

The Leading Zeroes for a number can be printed using the format string "D" in .NET . Below is a samp...

How to Group Digits of a Number for Formatting in C# ?

If you want to group the digits of a number for formatting to display in C# , one could use the "N" ...