Created
November 19, 2013 03:59
-
-
Save gshackles/7540109 to your computer and use it in GitHub Desktop.
Fun with value converters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", ""); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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