You can use ctype_digit()
to check if string contains only numbers. is_numeric()
accepts fractional numbers, negative numbers and plus sign.
var_dump(is_numeric(-1.33)); //true
var_dump(is_numeric(+1.33)); //true
Change:
$regular = "/^[0-9]*$/";
if(preg_match($regular, $this->cpf)){
if(!is_numeric($this->cpf)){
echo "O campo CPF só poderá conter Números";
die;
}
To:
if(!ctype_digit("$this->cpf")){
echo "O campo CPF só poderá conter Números";
die;
}
If you really want to use regex, you can use #^\d{11}$#
which says that the string must have exactly eleven digits.
You can refactor this function to:
function formatacao_cpf_func(){
$tamanhoCPF = strlen($this->cpf);
if(!ctype_digit("$this->cpf") || $tamanhoCPF != 11) die('O campo CPF é inválido');
echo "CPF foi digitado corretamente </br>";
$arr = str_split($str, 3);
printf('%s.%s.%s-%s', ...$arr);
}
Basically where they had two if, the conditions were now pooled to tell whether the input (cpf) is valid or not.
The way cpf is formatted has changed first the string is converted into an array separated by three characters each element ie four elements of length of 3 and the last one as 2
printf()
or sprintf()
" mount a mask based on the format. Remember that ...
(ellipsis) only works from php5 .6 forward in earlier versions you need to specify array indexes or use the vprintf()
function.
In the regex version the size is already validated along with the numeric characters.
function formatacao_cpf_func($cpf){
$regex = '#^\d{11}$#';
if(!preg_match($regex, $cpf)) die('O campo CPF é inválido');
echo "CPF foi digitado corretamente </br>";
$arr = str_split($cpf, 3);
printf('%s.%s.%s-%s', ...$arr);
}