/// <summary>
/// Formats a UK phone number correctly
/// </summary>
/// <param name="htmlHelper" />
/// <param name="telephone" />The string version of the telephone number with no spaces.
/// <returns></returns>
public static MvcHtmlString PhoneNumber(this HtmlHelper htmlHelper, string telephone)
{
Match match;
if (telephone != null)
{
if (telephone.StartsWith("02"))
{
match = Regex.Match(telephone, @"(\d{3})(\d{4})(\d+)");
}
else if (telephone.StartsWith("011") || Regex.IsMatch(telephone, @"^01\d1\d+")) //starts 011 or 01x1
{
match = Regex.Match(telephone, @"(\d{4})(\d{3})(\d+)");
}
else if (telephone.StartsWith("01") || telephone.StartsWith("07"))
{
match = Regex.Match(telephone, @"(\d{5})(\d+)");
}
else if (telephone.Length == 11)
{
match = Regex.Match(telephone, @"(\d{4})(\d{3})(\d+)");
}
else if (telephone.Length == 10)
{
match = Regex.Match(telephone, @"(\d{4})(\d+)");
}
else
{
match = Regex.Match(telephone, @"(\d{5})(\d+)");
}
if (Regex.IsMatch(telephone, @"^01\d1\d+"))
{
return MvcHtmlString.Create($"{match.Groups[1]}-{match.Groups[2]} {match.Groups[3]}");
}
List numberChunks = new List();
if (match.Success)
{
for (int i = 1; i < match.Groups.Count; i++)
{
numberChunks.Add(match.Groups[i].Value);
}
}
return MvcHtmlString.Create($"{string.Join(" ", numberChunks)}");
}
return null;
}
Tuesday, 25 February 2020
C# MVC UK Phone Numbers
How to format a telephone number as a UK standard format, according to https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers with MVC HtmlHelper in C#
Subscribe to:
Post Comments (Atom)
C# MVC UK Phone Numbers
How to format a telephone number as a UK standard format, according to https://en.wikipedia.org/wiki/National_conventions_for_writing_telep...
-
Gitflow branching with Atlassian JIRA, Bitbucket and Bamboo with Octopus Deploy doing branching UAT deployments. Snappy title I know but i...
-
How to format a telephone number as a UK standard format, according to https://en.wikipedia.org/wiki/National_conventions_for_writing_telep...
No comments:
Post a Comment