Validate characters only with letters and spaces (including accents)

Asked

Viewed 1,789 times

1

How can I validate a string and accept only letters with or without accent and spaces? I read a little about the ctype_alpha, but it didn’t work with accented lyrics, although I set the configs to pt_br:

setlocale(LC_ALL, 'pt_BR', 'pt_BR.UTF-8', 'pt_BR.UTF-8', 'portuguese');

1 answer

1


The function ctype_alpha only checks if the characters are in the range A-Za-z. One option is to use preg_match with the expression [\pL\s]+ to correspond only to letters and spaces.

function validar($string) {
    return !!preg_match('|^[\pL\s]+$|u', $string);
}

var_dump(validar("joÃO Maria")); // true
var_dump(validar("joao12"));     // false
var_dump(validar("Joao"));       // true
var_dump(validar("J0ao"));       // false
var_dump(validar(" "));          // true

The !! before the preg_match is used to return the boolean result.

The modifier u in regular expression is to treat the string like UTF-8.

  • Thank you, I didn’t know !!

  • UTF-8 is the best "filter"? I did some tests and sometimes it doesn’t pass, when I remove the "u" it gets ?? in the accents, but it works

  • @NGTHM4R3 I think it is relative. What words for example do not pass the test?

  • Like, actually something strange is happening, I test my form by sending the requests without filling out the form, so it makes a mistake, but when I send the data of the form itself it accepts the validation, what will it be? and something from html "charset"?

  • @NGTHM4R3 Would it not be more appropriate to use the isset before checking whether the variable has been defined?

  • 1

    Yes, it is already properly "handled", is that as my form is also validated by jquery, it is more practical to test already sending a request ready, but the normal use is by the same form.

  • How can I add numbers to this validation?

Show 2 more comments

Browser other questions tagged

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