Check special characters input

3

I'm trying to validate my form and capture special characters using preg_match(..., ...) , but with no success. Either using @ or without it, I get the following message:

  

Special characters detected, if you are using @ , remove it.

What's wrong with this code?

<?php
if (isset($_POST['ttrSignin'])) {
  $ttrUsername = trim(filter_input(INPUT_POST, 'ttrUsername'));
  $ttrPassword = trim(filter_input(INPUT_POST, 'ttrPassword'));

  if (empty($ttrUsername)) {
    $error[] = 'Insira seu nome de usuário do Twitter.';
  } elseif (empty($ttrPassword)) {
    $error[] = 'Insira sua senha do Twitter.';
  } elseif (!preg_match("/^[a-zA-Z'-]+$/", $ttrUsername)) {
    $error[] = 'Caracteres especiais detectados, se tiver usando <strong>@</strong>, remova-o.';
  } else {
    #restante do codigo
  }
  ?>
    
asked by anonymous 28.06.2017 / 18:31

1 answer

3

A basic example of block special characters is:

if (preg_match('/^[a-zA-Z0-9]+/', $username) {
    echo 'Username OK!';
}
else {
    echo 'Username tem caracteres inválidos...';
}

In your case you can do this:

elseif (!preg_match('/^[a-zA-Z0-9]+/', $ttrUsername)) {
  $error[] = 'Caracteres especiais detectados, se tiver usando <strong>@</strong>, remova-o.';
}

Ready. See if it works!

    
28.06.2017 / 18:57