0

please help to validate my username

i know its simple but i can't get it

i want only to validate the first 4 input of the username should be a letter.

i try to use the preg_match function but i can't get it correctly.

5
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by mschroeder
0

This should check the username must start with 4 digit letter followed by numbers or letters.

preg_match('/^[A-Za-z]{4}[A-Za-z0-9]+$/', $username, $matches);

Edited by paulrajj: n/a

0

Are you trying to just validate that the first four characters of a username consists of alphabetic characters?

You can use the "substr" function:

$username = "MyUser";
if(preg_match('/[A-Za-z]/', substr('abcdef', 0, 4)) {
    $valid = true;
}
else {
    $valid = false;
}
1
$array = array(str_split($string, 4));
if(!is_numeric($array['0']))
{
echo "Te first 4 are letters";
}
else
{
echo "the first 4 are not letters";
}

Haven't tested this yet so please tell if it didn't work.

Edited by d3rck: n/a

0
<?php
$subjects = array(
	'abcd124',
	'abc1234',
	'passesTheTest',
	'fai1TheTest',
        'abc',
        '123',
);

$pattern = '/^[a-zA-Z]{4}/';

foreach( $subjects as $test ){
	if( preg_match( $pattern, $test ) > 0 ){
		echo 'pass'.PHP_EOL;
	} else {
		echo 'fail'.PHP_EOL;
	}
}
pass
fail
pass
fail
fail
fail
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.