Jump to content

Validation of text box


rocky_88

Recommended Posts

I'm unable to validate my text box which should contain only alphabets.

 

Here is the code

 

$string=preg_match("/^[a-zA-Z]+$/",$string);
if($string)
{
echo "Valid";
}
else
{
echo "Invalid";
}

 

Even though the textbox contains only alphabets, it shows invalid.

 

I dont know what i'm doing wrong here.

 

However, if I leave a space inside the character class, it validates the string.

I've checked the output of the string and there are no spaces what so ever, yet it shows invalid.

Link to comment
https://forums.phpfreaks.com/topic/251434-validation-of-text-box/
Share on other sites

This code uses your pattern; try it and see what results you get.

 

<?php
$strings = array('thisisastring', 'thishas9numbers', 'this has spaces', 'alsoaSTRING', 'special_%ch$arac#ter!s');
foreach( $strings as $string ) {
$valid = preg_match("/^[a-zA-Z]+$/",$string);
echo "<i>$string</i>";
if($valid) {
	echo " is Valid";
} else {
	echo " is Invalid";
}
echo '<br>';
}

[/code]

I think I see why you're having issues. If you are assigning the result of preg_match() to the $string variable, it's important to understand what values may be returned from preg_match() . . .

 

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.