Change input border color

Asked

Viewed 5,340 times

0

I have an input that takes the user’s Cpf and the validation is done in php.

class CPF {

protected $field_id;

public function __construct( $field_id ) {
    $this->field_id = $field_id;
}

/**
 * Check if provided CPF is valid
 *
 * This method performs several verification including
 * the Brazilian Federal Revenue algorithm.
 *
 * @link https://www.geradorcpf.com/algoritmo_do_cpf.htm
 *
 * @return bool If it's valid or not.
 */
public function is_valid() {

    if ( empty( $this->field_id ) ) {
        wp_die( 'Ocorreu um erro na validação do CPF. Por favor, entre em contato com o administrador.' );
    }

    // Get posted field and make and remove any characters but numbers.
    $cpf = preg_replace( '/[^0-9]/', '', Input::get_unverified_posted( 'field_' . $this->field_id ) );

    // Add leading zeros in order to make sure the value has exact 11 characters.
    $cpf = str_pad( $cpf, 11, '0', STR_PAD_LEFT );

    // Check required length.
    if ( strlen( $cpf ) != 11 ) {
        return false;
    }

    // Check for dummy repeated sequence. Ex: 111.111.111-11.
    if ( preg_match( '/(\d)\1{10}/', $cpf ) ) {
        return false;
    }

    // Check against Brazilian Federal Revenue algorithm.
    for ( $t = 9; $t < 11; $t++ ) {
        for ( $d = 0, $c = 0; $c < $t; $c++ ) { // @codingStandardsIgnoreLine WordPress.CodeAnalysis.AssignmentInCondition
            $d += $cpf{$c} * ( ( $t + 1 ) - $c );
        }
        $d = ( ( 10 * $d ) % 11 ) % 10;
        if ( $cpf{$c} != $d ) {
            return false;
        }
    }
    return true;
}

}

But to make it easier for the user, I wanted the moment he enters the CPF if he does not obey the rule the field to have the red border.

But I only have access to the input class, because it is generated by u plugin, which makes a foreach, there is some way I can do this only with id which in my case is id="field_13".

  • I modified the question, in the other the user used the Pattern, I think it will not work here.

1 answer

1


Use the onKeyup event in the input and if the validation does not satisfy, add a 'has-error' class in it. If the validation meets, remove the above class.

Below I implemented to be an example for you:

const inputCpfElement = document.getElementById('inputCpf');

inputCpfElement.addEventListener('keyup', function(ev) {
  const input = ev.target;
  const value = ev.target.value;

  if (value.length <= 3) {
    input.classList.add('--has-error');
    
  } else {
    input.classList.remove('--has-error');
  }
});
.field {
  border: 1px solid #ccc;
  outline: none;
}

.field.--has-error {
  border-color: #f00;
}
<p>Valida se o tem mais de 3 caracteres digitados.</p>
<form>
  <label>Cpf: <input type="text" id="inputCpf" class="field" /></label>
</form>

Browser other questions tagged

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