Home > Enterprise >  How do I change my mask dynamically on Xamarin Forms?
How do I change my mask dynamically on Xamarin Forms?

Time:12-07

I have an input where the user enters a bank account number, and I need to mask it with the syntax "XXXX-X", where the length of the string before the hyphen varies between 4 and 13 digits, and the last digit must be always preceded with an hyphen, which must be added automatically, and not inputed by the user. The way I'm doing it is:

<customcontrols:BorderlessEntry Text="{Binding Account}"
        Placeholder="0000000-0"
        Keyboard="Numeric" 
        MaxLength="14"
    <customcontrols:BorderlessEntry.Behaviors>
        <b:MaskedBehavior Mask="XXXXXXX-X" MinLength="6" MaxLength="14" />
    </customcontrols:BorderlessEntry.Behaviors>
</customcontrols:BorderlessEntry>

In this code, the length of the mask is fixed, and I need it to be dynamic. Is there an way to do this?

The code I'm already using for masking behavior is similar to this

I've tried some approaches, like changing the text directly in the input through entry.Text, but I haven't succeeded

CodePudding user response:

Here's how I've done it

void AccountEntry_TextChanged(object sender, TextChangedEventArgs e)
{
    if (!string.IsNullOrEmpty(e.NewTextValue) && e.NewTextValue.Length > 4)
        accountEntry.Text = HandleAccount(e.NewTextValue);
}

string HandleAccount(string input)
{
    if (input.Contains("-"))
    {
        input = input.Replace("-", "");
    }

    string result = string.Format("{0}-{1}", input.Substring(0, input.Length - 1), input[input.Length - 1]);

    return result;
}
  • Related