Skip to content

Instantly share code, notes, and snippets.

@gshackles
Created November 19, 2013 03:59
Show Gist options
  • Save gshackles/7540109 to your computer and use it in GitHub Desktop.
Save gshackles/7540109 to your computer and use it in GitHub Desktop.
Fun with value converters
public class CreditCardNumberValueConverter : MvxValueConverter
{
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var builder = new StringBuilder(Regex.Replace(value.ToString(), @"\D", ""));
foreach (var i in Enumerable.Range(0, builder.Length / 4).Reverse())
builder.Insert(4*i + 4, " ");
return builder.ToString().Trim();
}
public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Regex.Replace(value.ToString(), @"\D", "");
}
}
public class PhoneNumberValueConverter : MvxValueConverter
{
public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var numbers = Regex.Replace(value.ToString(), @"\D", "");
if (numbers.Length <= 3)
return numbers;
if (numbers.Length <= 7)
return string.Format("{0}-{1}", numbers.Substring(0, 3), numbers.Substring(3));
return string.Format("({0}) {1}-{2}", numbers.Substring(0, 3), numbers.Substring(3, 3), numbers.Substring(6));
}
public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Regex.Replace(value.ToString(), @"\D", "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment