Hi everybody.

I'm having a problem with preg_match function.

I have a field where I want to allow only letter or numbers, but no spaces or any special characters (field is for login name).

I'm using a preg_match for it that look like this:

function validateTextOnlyNoSpaces($theinput, $description = ''){
$result = preg_match ("/^[A-Za-z0-9]/", $theinput );
if ($result){
return true;
}else{
$this->errors[] = $description;
return false;
}
}

after I'm calling it like this

$name = $_POST['n_user'];
$theValidator->validateTextOnlyNoSpaces($name, 'User login cannot contain spaces');

but the function returns error "no spaces allowed" even when there are no spaces in the name.

Anybody knows what's wrong in my function.
Thanks.

    Added +$ to the Regular expression. You may want to change it to *$ if you want to allow blank values. (if you checking required($value, $description) else where within your class.

    function validateTextOnlyNoSpaces($theinput, $description = ''){
    $result = preg_match ("/^[A-Za-z0-9]+$/", $theinput );
    if ($result){
    return true;
    }else{
    $this->errors[] = $description;
    return false;
    }
    } 
    

      Thanks for solutions, both worked 🙂

      I got another question thought.

      I got few extra validation in place (only digits, not empty, etc.). But I also need an email validation.
      I would need to check it for @ and at least 1 . (period)

      So somechars@morechars.co.uk will pass validation, but somechars@localhost won't.

      How should I formulate the expression inside the preg_match function.

      Thanks

        If you want to validate e-mail addresses, look into using [man]filter_var/man with the FILTER_VALIDATE_EMAIL filter/option.

          Write a Reply...