trim() Validation
July 15th, 2008
While writing a fairly standard sign-up/log-in system, I got to the point of validating the password to make sure it only contained acceptable characters. Now for me this would usually mean a regular expression. But, since this system wasn’t for me I decided to make the “valid characters” configurable, and generally the people configuring it won’t be able to write a regular expression.
My solution is to use php’s trim() (or more specifically rtrim(), but it doesn’t really matter) by passing the users input as the first argument, and the string of valid characters as the second; I should get an empty string in return. So the test, only allowing lowercase letters, becomes:
if ('' !== rtrim($input, 'abcdefghijklmnopqrstuvwxyz')) {
return false;
}
Simple! I don’t know how it compares speed wise with other methods, but it seems simple and effective and I can’t imagine it’s terribly slow unless your strings get larger.
I’m also not sure how it would handle multi-byte characters. But I don’t think it would be a problem if it doesn’t. Anyone got any insight?




Interesting approach,
I do like it though, this post is a month or so old, so have you found problems with it?
Seem like a pretty simple way to do it and I don’t see why it would have any speed problems.
Nice one B
Comment by Merkin — 2008-08-19 @ 12:23
No, haven’t found any problems with it thus far. It’s still live.
The speed concerns I mentioned where only for when the list of valid characters get considerably longer, I don’t know how efficient trim is in that case. But it’s probably not worse than the common regex approach in that regard.
Comment by Brenton Alker — 2008-08-23 @ 11:27