Change Input Border Color

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){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, he wanted the moment he typed the CPF if he did not obey the rule the field would have the red border.

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

    
asked by anonymous 28.11.2018 / 18:10

1 answer

0

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

I have implemented the following as 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>
    
28.11.2018 / 18:45