JavaScript

Document field

A field that masks and validates a CPF, CNPJ, CEP or phone number as you type, with Brazilian Utils in React, Angular, Vue and plain JavaScript.

A field that formats as you type, inside a form that validates. Each example runs the code below it, which you can copy as is.

The field only masks, and hands the form the value without its mask, with parse*, so a form holds 52998224725 and a submit sends that. Validation belongs to the form, which also leaves one error message per field instead of two. The mask is the same everywhere: a formatter takes whatever has been typed so far, and formatting what comes before the caret says where the caret goes, so editing in the middle works.

The hook owns the input: it takes the formatter and the value the form holds, masks what is typed and says so through its own onChange. React never writes the input's value, which is what would undo a mask. The field takes the input's own props, so react-hook-form's field spreads into it as is:

Loading the demo…

import { formatCpf, parseCpf } from "@brazilian-utils/brazilian-utils";
import { Field } from "./field";

type CpfFieldProps = {
  /** The CPF without its mask, the way the form holds it. */
  value: string;
  /** Called with the CPF without its mask. */
  onChange: (value: string) => void;
  /** What the form says is wrong with the value, if anything. */
  errorMessage?: string;
};

/** The field of the form, with what makes it a CPF and nothing else. */
export function CpfField(props: CpfFieldProps) {
  return (
    <Field
      {...props}
      label="CPF"
      inputMode="numeric"
      autoComplete="off"
      placeholder="000.000.000-00"
      mask={{ format: formatCpf, parse: parseCpf }}
    />
  );
}

Loading the demo…

Loading the code…

Loading the demo…

Loading the code…

Loading the demo…

Loading the code…

A ControlValueAccessor, so it takes formControlName (or formControl, or ngModel) like a native input, touched on blur and disabled with its control. The validator is a ValidatorFn on the control:

Loading the demo…

Loading the code…

Loading the demo…

Loading the code…

Loading the demo…

Loading the code…

Loading the demo…

Loading the code…

The value is the component's v-model (defineModel), which is what VeeValidate's defineField binds to, and the rule lives in the form's schema:

Loading the demo…

Loading the code…

Loading the demo…

Loading the code…

Loading the demo…

Loading the code…

Loading the demo…

Loading the code…

No build step: save it as an .html file and open it. It imports the package from a CDN, masks on input and validates on submit, moving focus to the field it rejects.

Loading the demo…

cpf-field.html

Loading the code…

Loading the demo…

cnpj-field.html

Loading the code…

Loading the demo…

cep-field.html

Loading the code…

Loading the demo…

phone-field.html

Loading the code…

The utilities reference lists every function.