Check input special characters

Asked

Viewed 1,872 times

1

I’m trying to validate my form and capture special characters using preg_match(..., ...), but unsuccessfully. So much using @ or without it, returns me the following message:

Special characters detected if 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
  }
  ?>
  • What do you call special characters? Single quotes and double quotes can go through regex? Several blank spaces are acceptable?

1 answer

1

A basic example of block off 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 it:

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

Ready. See if it works!

  • It worked but does it block all the same?

Browser other questions tagged

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