67 lines
2.1 KiB
C#
67 lines
2.1 KiB
C#
using System.Windows.Forms;
|
|
|
|
namespace UI
|
|
{
|
|
/// <summary>
|
|
/// Formata CPF ou CNPJ automaticamente enquanto o usuário digita.
|
|
/// Uso: DocumentoHelper.Registrar(txtDocumento);
|
|
/// </summary>
|
|
public static class DocumentoHelper
|
|
{
|
|
public static void Registrar(RoundTextBox txt)
|
|
{
|
|
bool formatando = false;
|
|
|
|
txt.TextChanged += (_, _) =>
|
|
{
|
|
// Evita loop: TextChanged → altera Text → TextChanged → ...
|
|
if (formatando) return;
|
|
formatando = true;
|
|
|
|
try
|
|
{
|
|
// 1. Extrai só os dígitos
|
|
string digits = new string(txt.Text.Where(char.IsDigit).ToArray());
|
|
|
|
// 2. Limita ao tamanho máximo do CNPJ
|
|
if (digits.Length > 14) digits = digits[..14];
|
|
|
|
// 3. Formata conforme o tamanho
|
|
string formatado = digits.Length <= 11
|
|
? FormatarCPF(digits)
|
|
: FormatarCNPJ(digits);
|
|
|
|
// 4. Só atualiza se realmente mudou
|
|
if (txt.Text != formatado)
|
|
{
|
|
txt.Text = formatado;
|
|
txt.SelectionStart = formatado.Length; // cursor no final
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
formatando = false;
|
|
}
|
|
};
|
|
}
|
|
|
|
// CPF: 000.000.000-00
|
|
private static string FormatarCPF(string d) => d.Length switch
|
|
{
|
|
<= 3 => d,
|
|
<= 6 => $"{d[..3]}.{d[3..]}",
|
|
<= 9 => $"{d[..3]}.{d[3..6]}.{d[6..]}",
|
|
_ => $"{d[..3]}.{d[3..6]}.{d[6..9]}-{d[9..]}"
|
|
};
|
|
|
|
// CNPJ: 00.000.000/0000-00
|
|
private static string FormatarCNPJ(string d) => d.Length switch
|
|
{
|
|
<= 2 => d,
|
|
<= 5 => $"{d[..2]}.{d[2..]}",
|
|
<= 8 => $"{d[..2]}.{d[2..5]}.{d[5..]}",
|
|
<= 12 => $"{d[..2]}.{d[2..5]}.{d[5..8]}/{d[8..]}",
|
|
_ => $"{d[..2]}.{d[2..5]}.{d[5..8]}/{d[8..12]}-{d[12..]}"
|
|
};
|
|
}
|
|
} |