How to prevent user registration with Login initiated by number or symbol

4

I would like the help of you to do the following I have in case this function that makes in the case the verification of the login to be registered of the user.

If it starts with a number it sends a warning to prevent registration. If you did not eat by number, it frees you from registering for this login.

Here's my problem: this function will inhibit the registration of logins initiated by any symbol or character other than a letter of the alphabet such as @! # $% ¨ ". + § = * / 8 among others or initiated by Below is the function I did.

<?php if(is_numeric(substr($loginPost,0,1))){ ?>
         o Login não pode começar com numero
  <?} else { ?>
          Usuário Cadastrado
   <? } ?>
    
asked by anonymous 11.11.2014 / 00:26

2 answers

8

You can perform this validation in several ways, one of which is a regular expression that matches a range of characters (a-z) at the beginning. i means that the combination is made without differentiating uppercase. The function that does search with regex is preg_match ()

<?php  
$logins = array('Admin', '007_bond', 'adm', '@dmin');

$regex = '/^[A-Z]/i';

foreach($logins as $item){
    if(preg_match($regex, $item)){
        echo 'login: '. $item .' valido <br>';
    }else{
        echo 'login: '. $item .' invalido <br>';
    }

}   

The other way is to use the ctype_alpha function in the first character of the string that in the example is $item[0] .

<?php
$logins = array('Admin', '007_bond', 'adm', '@dmin');

foreach($logins as $item){
    if(ctype_alpha($item[0])){
        echo 'login: '. $item .' valido <br>';
    }else{
        echo 'login: '. $item .' invalido <br>';
    }

}

Example

    
11.11.2014 / 01:16
6

I have adapted your own logic:

<?php
   $ascii = ord( strtoupper( $loginPost ) );

   if( $ascii < 65 || $ascii > 90 ) {
      echo 'o Login precisa comecar com uma letra';
   else
      echo 'Usuario Cadastrado';
   }
?>


Explaining:

This function returns the string converted to uppercase:

strtoupper ( $loginPost );

And this returns the ASCII code of the first character of the string :

$ascii = ord( $string );

It is enough to compare if it is less than ord( 'A' ) (65) or greater than ord( 'Z' ) (90):

if( $ascii < 65 || $ascii > 90 ) { ...

... and display the desired message.


More traditional alternative

The above code is equivalent to this, but I wanted to start by introducing less common functions;)

<?php
   $letra = strtoupper( $loginPost[0] );

   if( $letra < 'A' || $letra > 'Z' ) {
      echo 'o Login precisa comecar com uma letra';
   else
      echo 'Usuario Cadastrado';
   }
?>


Addendum:

$loginPost[0] and substr( $loginPost, 0, 1) are the same in this case. Just be careful when you use multibyte strings, because there is no escaping something like this:

$letraMultiByte = mb_substr( $loginPost, 0, 1, 'utf-8' );
    
11.11.2014 / 02:55