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
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]

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.