开发者

Zend Framework: why does whitespace validate against my regular expression?

I have the following code:

$sfKeyword = new Zend_Form_SubForm();

$tfKeyword = $sfKeywords->createElement('text', 'keyword');
$tfKeyword->setLabel('Keyword: ');
$tfKeyword->addValidator('regex', false, array('/[a-zA-开发者_如何学GoZ_][a-zA-Z_0-9]*/'));

This regex validates keywords and is supposed to allow only a-z, A-Z, and _ as the first characters and then additionally allowing digits 0-9, zero or more occurrences.

But when entering some string with whitespace in between, the string passes the validator without error message. This shouldn't be the case.

Note, I've also tried

'/[a-zA-Z_][a-zA-Z_0-9]*/s'

but there's no difference (as expected).

What's wrong with the regex (or Zend Framework)?


The problem is that your regex is not anchored. That means that as long as some part of the string matches the regex, the regex will match. Instead, anchor it:

/^[a-zA-Z_][a-zA-Z_0-9]*$/

The leading ^ character says "The start of the string", and the trailing $ means "The end of the string". So now it will match any string that starts with [a-zA-Z_] and then is followed by one or more [a-zA-Z_0-9] until the end of the string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜