String validation
String validation – Validation for strings.
Introduction to String validation
This method validates string using the given format.
This method takes two arguments:
- String.
- An array of options.
Various option are:
format
[mixed] - Format of the string-
VALIDATE_NUM
- Number [0-9]. -
VALIDATE_SPACE
- Space [\s]. -
VALIDATE_ALPHA_LOWER
- Lower case alphabets [a-z]. -
VALIDATE_ALPHA_UPPER
- Upper case alphabets [A-Z]. -
VALIDATE_ALPHA
- Alphabets [a-Z]. -
VALIDATE_EALPHA_LOWER
- Lower case letters with an accent [French, ...], umlauts [German], special characters [e.g. Skandinavian] andVALIDATE_ALPHA_LOWER
. -
VALIDATE_EALPHA_UPPER
- Upper case letters with an accent [French, ...], umlauts [German], special characters [e.g. Skandinavian] andVALIDATE_ALPHA_UPPER
. -
VALIDATE_EALPHA
- Letters with an accent [French, ...], umlauts [German], special characters [e.g. Skandinavian] andVALIDATE_ALPHA
. -
VALIDATE_PUNCTUATION
- Punctuation .,;:&"?!', "[" and "]". -
VALIDATE_NAME
-VALIDATE_EALPHA
,VALIDATE_SPACE
, "'" and "-". -
VALIDATE_STREET
-VALIDATE_NUM
andVALIDATE_NAME
, "\./", "º" and "ª".
-
-
min_length
[int] - Minimum length. -
max_length
[int] - Maximum length.
How to use String Validation
String Validation
The following example assumes that one wants to validate a string when only uppercase alphabets, numbers and space are allowed
I am trying to verify in PHP with preg_match that an input string contains only "a-z, A-Z, -, _ ,0-9" characters. If it contains just these, then validate.
I tried to search on google but I could not find anything usefull.
Can anybody help?
Thank you !
asked Dec 27, 2012 at 15:10
1
Use the pattern '/^[A-Za-z0-9_-]*$/'
, if an empty string is also valid. Otherwise '/^[A-Za-z0-9_-]+$/'
So:
$yourString = "blahblah";
if [preg_match['/^[A-Za-z0-9_-]*$/', $yourString]] {
#your string is good
}
Also, note that you want to put a '-' last in the character class as part of the character class, that way it is read as a literal '-' and not the dash between two characters such as the hyphen between A-Z.
answered Dec 27, 2012 at 15:12
DWrightDWright
9,1884 gold badges35 silver badges53 bronze badges
2
$data = 'abc123-_';
echo preg_match['/^[\w|\-]+$/', $data]; //match and output 1
$data = 'abc..';
echo preg_match['/^[\w|\-]+$/', $data]; //not match and output 0
answered Dec 27, 2012 at 15:18
LevinLevin
1945 bronze badges
You can use preg_replace[$pattern, $replacement, $subject]:
if [preg_replace['/[A-Za-z0-9\-\_]/', '', $string]] {
echo "Detect non valid character inside the string";
}
The idea is to remove any valid chars, if the result is NOT empty do the code.
answered Jul 5, 2018 at 12:08