在这个沙盒项目中,可以看到以下方法的使用,在输入中应用它们:https ://codesandbox.io/s/epic-darwin-obj8dp
正则表达式掩码:
// 10.000,00
const maskMoney = (event) => {
const { value } = event.currentTarget;
return value
.replace(/\D/g, '')
.replace(/(\d)(\d{2})$/, '$1,$2')
.replace(/(?=(\d{3})+(\D))\B/g, '.');
};
// 000.000.000-00
const maskCPF = (event) => {
event.currentTarget.maxLength = 15;
const { value } = event.currentTarget;
return value
.replace(/\D/g, '')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d{1,2})/, '$1-$2')
.replace(/(-\d{2})\d+?$/, '$1');
};
// 00.000.000/0000-000
const maskCNPJ = (event) => {
event.currentTarget.maxLength = 18;
const { value } = event.currentTarget;
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1.$2')
.replace(/(\d{3})(\d)/, '$1/$2')
.replace(/(\d{4})(\d{2})/, '$1-$2');
};
// 000.000.000-00 or 00.000.000/0000-000
const maskCPFOrCNPJ = (event) => {
event.currentTarget.maxLength = 18;
const { value } = event.currentTarget;
if (value.length >= 15) {
return maskCNPJ(event);
}
return maskCPF(event);
};
// (00) 00000-0000
const maskPhone = (event) => {
event.currentTarget.maxLength = 15;
const { value } = event.currentTarget;
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '($1) $2')
.replace(/(\d{5})(\d{4})/, '$1-$2');
};
// (00) 0000-0000
const maskLandlineTelephone = (
event,
) => {
event.currentTarget.maxLength = 14;
const { value } = event.currentTarget;
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '($1) $2')
.replace(/(\d{4})(\d{4})/, '$1-$2');
};
// 00000-000
const maskCEP = (event) => {
event.currentTarget.maxLength = 9;
const { value } = event.currentTarget;
return value.replace(/\D/g, '').replace(/^(\d{5})(\d{3})+?$/, '$1-$2');
};
// 00/00/0000
const maskDate = (event) => {
event.currentTarget.maxLength = 10;
const { value } = event.currentTarget;
return value
.replace(/\D/g, '')
.replace(/(\d{2})(\d)/, '$1/$2')
.replace(/(\d{2})(\d)/, '$1/$2')
.replace(/(\d{4})(\d)/, '$1');
};
const maskOnlyLetters = (event) => {
const { value } = event.currentTarget;
return value.replace(/[0-9!@#¨$%^&*)(+=._-]+/g, '');
};
const maskOnlyNumbers = (event) => {
const { value } = event.currentTarget;
return value.replace(/\D/g, '');
};