Monday, 19 August 2013

Should I use regex, or just a series of if statements?

Should I use regex, or just a series of if statements?

I need to validate a string against these rules:
Value is not s
Value is at least 1 character long
Value contains only a-z0-9-_/
Value does not begin with /
Value does not end with /
Value does not contain /s/
Value does not contain //
Value does not begin with s/
Value does not end with /s
(More simply, I am looking for something that resembles a UNIX-style path,
with a slash separator, where file/folder names allow only a-z0-9-_, no
file/folder is named s, and it does not having a beginning or trailing
slash.)
I need to do this on the client-side via JavaScript and on the server-side
using PHP.
I know that the most elegant solution would be via a complex regular
expression. But is it worth the challenge of trying to write one? Or
should I just use conditions?
Right now, my solution is this: http://jsfiddle.net/cKfnW/
JavaScript:
(function ($) {
var test = function (val) {
return
val != 's' &&
/^[a-z0-9-_\/]+$/.test(val) &&
val.substr(0, 1) != '/' &&
val.substr(val.length-1) != '/' &&
val.search('/s/') == -1 &&
val.search('//') == -1 &&
val.substr(0, 2) != 's/' &&
val.substr(val.length-2) != '/s';
};
$('#test')
.keyup(function () {
if (test($(this).val())) {
$(this).removeClass('fail').addClass('pass');
}
else {
$(this).removeClass('pass').addClass('fail');
}
)
.keyup();
})(jQuery);
PHP:
<?php
function test ($val) {
return
$val != 's' &&
preg_match('/^[a-z0-9-_\/]+$/', $val) &&
substr($val, 0, 1) != '/' &&
substr($val, -1) != '/' &&
strpos($val, '/s/') === false &&
strpos($val, '//') === false &&
substr($val, 0, 2) != 's/' &&
substr($val, -2) != '/s';
}
die (test($_GET['test']) ? 'pass' : 'fail');
?>
Is this acceptable practice? I'm not very good at regex, and I have no
idea how to write one for this -- but I can't help feeling like this is
more of a hack than a solution.
What do you think?
Thanks.

No comments:

Post a Comment