Create a Mask for Cpf using Xamarin

Asked

Viewed 4,613 times

4

Hello, I would like to create a Cpf mask using edittext, but I did not succeed; I searched the net and found several examples in java, but I could not adapt to c#, someone could help me?

Thanks in advance.

  • Jose Roberto you would have this project shared on Github?

  • https://github.com/Altevir/xamarinforms-mask-behaviors

3 answers

5

I gave an improved code to facilitate the reuse of the code, follows below:

public class Mask : Java.Lang.Object, ITextWatcher
{
    private readonly EditText _editText;
    private readonly string _mask;
    bool isUpdating;
    string old = "";

    public Mask(EditText editText, string mask)
    {
        _editText = editText;
        _mask = mask;
    }

    public static string Unmask(string s)
    {
        return s.Replace(".", "").Replace("-", "")
            .Replace("/", "").Replace("(", "")
            .Replace(")", "");
    }

    public void AfterTextChanged(IEditable s)
    {
    }

    public void BeforeTextChanged(ICharSequence s, int start, int count, int after)
    {
    }

    public void OnTextChanged(ICharSequence s, int start, int before, int count)
    {
        string str = Unmask(s.ToString());
        string mascara = "";

        if (isUpdating)
        {
            old = str;
            isUpdating = false;
            return;
        }

        int i = 0;

        foreach (var m in _mask.ToCharArray())
        {
            if (m != '#' && str.Length > old.Length)
            {
                mascara += m;
                continue;
            }
            try
            {
                mascara += str[i];
            }
            catch (System.Exception ex)
            {
                break;
            }
            i++;
        }

        isUpdating = true;

        _editText.Text = mascara;

        _editText.SetSelection(mascara.Length);
    }
}

Call of Activity:

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
        var txtCpf = _view.FindViewById<EditText>(Resource.Id.txtCpf);
        txtCpf.AddTextChangedListener(new Mask(txtCpf, "###.###.###-##"));
}

4

Well, if anyone wants something simpler on PCL just add this function in the Textchanged from entry, textCell

        void cpfMask(object sender, EventArgs e)
        {
            var ev = e as TextChangedEventArgs;

            if (ev.NewTextValue != ev.OldTextValue)
            {
                var entry = (Entry)sender;
                string text = Regex.Replace(ev.NewTextValue, @"[^0-9]", "");

                text = text.PadRight(11);

                // removendo todos os digitos excedentes 
                if (text.Length > 11)
                {
                    text = text.Remove(11);
                }

                text = text.Insert(3, ".").Insert(7, ".").Insert(11, "-").TrimEnd(new char[] { ' ', '.', '-' });
                if (entry.Text != text)
                    entry.Text = text;

            }
        }

1

Good people, after a few hours studying, I managed to do and decided to share with you, in case someone has interest. In reality I simply adapted to c#, the original java code is at this link.

 protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);


        SetContentView(Resource.Layout.Main);

        et = FindViewById<EditText>(Resource.Id.edittext1);
        var ed = FindViewById<EditText>(Resource.Id.edittext2);

        insert("###.###.###-##", et);


       et.AddTextChangedListener(this);



    }
    public static string unmask(string s)
    {
        return s.Replace(".", "").Replace("-", "")
                .Replace("/", "").Replace("(", "")
                .Replace(")", "");
    }

    public void insert(string mask, EditText ediTxt)
    {
        _mask = mask;
        et = ediTxt;
    }

    public void AfterTextChanged(IEditable s)
    {
    }



    public void BeforeTextChanged(ICharSequence s, int start, int count, int after)
    {

    }

    public void OnTextChanged(ICharSequence s, int start, int before, int count)
    {
        string str = unmask(s.ToString());
        string mascara = "";

        if (isUpdating)
        {
            old = str;
            isUpdating = false;
            return;

        }

        int i = 0;

        foreach (var m in _mask.ToCharArray())
        {
            if (m != '#' && str.Length > old.Length)
            {
                mascara += m;
                continue;
            }
            try
            {
                mascara += str[i];
            }
            catch (Exception e)
            {

                break;
            }
            i++;
        }
        isUpdating = true;
        et.Text = mascara;
        et.SetSelection(mascara.Length);


    }
}

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.