Skip to content

Commit

Permalink
Merge pull request #12258 from eileenmcnaughton/alpha
Browse files Browse the repository at this point in the history
Add 'Alphanumeric' rule type
  • Loading branch information
seamuslee001 authored Jun 5, 2018
2 parents 6da5962 + d22982f commit f59c376
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
21 changes: 21 additions & 0 deletions CRM/Utils/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,27 @@ public static function numeric($value) {
return preg_match('/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/', $value) ? TRUE : FALSE;
}

/**
* Test whether $value is alphanumeric.
*
* Underscores and dashes are also allowed!
*
* This is the type of string you could expect to see in URL parameters
* like `?mode=live` vs `?mode=test`. This function exists so that we can be
* strict about what we accept for such values, thus mitigating against
* potential security issues.
*
* @see \CRM_Utils_RuleTest::alphanumericData
* for examples of vales that give TRUE/FALSE here
*
* @param $value
*
* @return bool
*/
public static function alphanumeric($value) {
return preg_match('/^[a-zA-Z0-9_-]*$/', $value) ? TRUE : FALSE;
}

/**
* @param $value
* @param $noOfDigit
Expand Down
7 changes: 7 additions & 0 deletions CRM/Utils/Type.php
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,7 @@ public static function validate($data, $type, $abort = TRUE, $name = 'One of par
'MysqlOrderBy',
'ExtensionKey',
'Json',
'Alphanumeric',
);
if (!in_array($type, $possibleTypes)) {
if ($isThrowException) {
Expand Down Expand Up @@ -537,6 +538,12 @@ public static function validate($data, $type, $abort = TRUE, $name = 'One of par
return $data;
}
break;

case 'Alphanumeric':
if (CRM_Utils_Rule::alphanumeric($data)) {
return $data;
}
break;
}

if ($abort) {
Expand Down
46 changes: 46 additions & 0 deletions tests/phpunit/CRM/Utils/RuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -132,4 +132,50 @@ public function testExtenionKeyValid($key, $expectedResult) {
$this->assertEquals($expectedResult, CRM_Utils_Rule::checkExtensionKeyIsValid($key));
}

/**
* @return array
*/
public function alphanumericData() {
$expectTrue = [
0,
999,
-5,
'',
'foo',
'0',
'-',
'_foo',
'one-two',
'f00'
];
$expectFalse = [
' ',
5.7,
'one two',
'one.two',
'A<B',
"<script>alert('XSS');</script>",
'(foo)',
'foo;',
'[foo]'
];
$data = [];
foreach ($expectTrue as $value) {
$data[] = [$value, TRUE];
}
foreach ($expectFalse as $value) {
$data[] = [$value, FALSE];
}
return $data;
}

/**
* @dataProvider alphanumericData
* @param $value
* @param $expected
*/
public function testAlphanumeric($value, $expected) {
$this->assertEquals($expected, CRM_Utils_Rule::alphanumeric($value));
}

}

0 comments on commit f59c376

Please sign in to comment.