Test
Test

Reputation: 63

How to check string start with character validation

I need to put validation that Name should not start with space, . or _

After entering name then after u can add.

Valid :
My Name
My.Name
My_Name

In Valid:
 My Name
_My Name
.My Name

I made a function

  function validName($name) {

    $name_first_character = substr($name, 0, 1);

    if ($name_first_character == '.' || $name_first_character == '-') {
      return FALSE;
    }
    return TRUE;
  }

But still it's not checking for space. Do I need to do with preg_match?

Upvotes: 1

Views: 266

Answers (3)

chris85
chris85

Reputation: 23880

A regex would probably be easier. You are missing some of the characters you don't want to allow. It also would be easier to write it with an in_array.

if (in_array($name_first_character, array('.', '-', ' ', '_'))) {
    return FALSE;
}

Demo: https://3v4l.org/SGM4T

A regex could be:

if (preg_match('/^[-._ ]/', $name)) {
    return FALSE;
}

Demo: https://3v4l.org/cu6vi

The space in the character class can be replaced with a \s if you want to disallow any type of white space.

^ is the start of the string
[] creates a character class and allows any 1 of the characters inside it. If a - is used and isn't at the start or end it will create a range. For example 1-9 would be numbers between 1 and 9.

Upvotes: 1

user9487972
user9487972

Reputation:

instead of checking for what you dont want, how about checking for what you do want

 function validName($name) {

  $name_first_character = substr($name, 0, 1);

   if (ctype_alpha($name_first_character)) { 
       return TRUE;
    }else{
       return FALSE;
    }

 }

Upvotes: 1

Kerry Gougeon
Kerry Gougeon

Reputation: 1337

To check for space, you could trim the string and compare if you still have the same variable. Something like would check for leading/trailing whitespace

$temp  = $text
$trimmed = trim($temp);
return $temp == $text

Upvotes: 0

Related Questions