wixel / gump Goto Github PK
View Code? Open in Web Editor NEWA fast, extensible & stand-alone PHP input validation class that allows you to validate any data
Home Page: https://wixelhq.com
License: MIT License
A fast, extensible & stand-alone PHP input validation class that allows you to validate any data
Home Page: https://wixelhq.com
License: MIT License
When testing the class, I had two php notices ("Notice: Use of undefined constant safe - assumed 'safe' in").
After investigation, you must replace (2 times) :
if(is_callable(array(safe, 'filter_'.$filter)))
by :
if(is_callable(array(__CLASS__, 'filter_'.$filter)))
Very nice project !
I have just extracted the full package and found the following error.
Parse error: syntax error, unexpected '"' in C:\wamp\www\wh\lib\gump.class.php on line 27
I noticed that the code assigns some strings to the public static $en_noise_words variable, specially the problem to my understanding is the $ in the assignment, which removed solves the error but of course the GUMP package won't work well,
please anyone help !
Hello,
Can we also trigger an error if there are too many fields to validate?
Let's say we have 4 fields to validate, but only 3 rules are specified. This should trigger an error or the field without rule should be left out of the $gump->run($_POST) return array.
What do you think? or is it already possible?
Roy
Before PHP 5.3.0 the checkdnsrr function didn't exist on Windows platforms.
See : http://php.net/manual/en/function.checkdnsrr.php
A small check or an alternative may be useful.
ipv4 vs ipv6 address validation is important to differentiate between.
This IP validator probably need to be extended slightly to accomodate 3 cases. Valid IP, Valid IPv4, Valid IPv6.
I feel the max_len needs to be re-written in the master version.
For example, a postcode is 4 digits, max_len,4
The output is: The postcode field needs to be shorter than 4 characters.
Which is incorrect, it needs to be 4 or less characters.
Either, the wording needs to change to "field needs to be $param or shorter in length"
or you need to increase the $param by one, as shown below.
case 'validate_max_len':
$param++;
if($param == 1) {
$resp[] = "The <span class=\"$field_class\">$field</span> field needs to be shorter than $param character";
} else {
$resp[] = "The <span class=\"$field_class\">$field</span> field needs to be shorter than $param characters";
}
break;
case 'validate_min_len':
$param--;
if($param == 1) {
$resp[] = "The <span class=\"$field_class\">$field</span> field needs to be longer than $param character";
} else {
$resp[] = "The <span class=\"$field_class\">$field</span> field needs to be longer than $param characters";
}
break;
As I suggested previously, it would be fine to be able to validate lastnames like "O'Hara".
The validate_valid_name aims to meet this requirement, but it fails when a simple quote is found.
I managed to get it working by adding the FLAG_NO_ENCODE_QUOTES flag to the filter_var() function in the sanitize() method and in the sanitize_string() filter.
Without this flag, the simple quote would be encoded in "'", and the preg_match would never match any lastname with simple quotes.
You have more hindsight on gump than me, so I let you decide if it this change is relevant or if it would be better to make this in another way.
At the moment you only seem to be able to have 'fieldname is invalid'. This is rarely particularly helpful to the end user. Thanks!
$G = new GUMP();
$data = $G->filter( $G->sanitize( $_POST, ['url','name'] ),[
'url' => 'trim|sanitize_string',
'name' => 'trim|sanitize_string',
]);
print_r( $data );
if I submit a field "something" in the post, it is still available in the print_r
As far as I see the only documentation is the readme.markdown and it's outdated. Is this project still alive and any chance of updating the documentation with full list of available validators and filters?
Hi,
Is it a good idea to introduce a regex validator?
The boolean
validator will accept virtually any value. In fact, I have yet to ever seen it fail. According to the documentation it is supposed to accept true
, "true", "yes", 1, false
, "false", "no", and 0. However, in my testing it accepts anything including "nada"...
Hi,
In the corrections you made yesterday, I can see a small mistake in the regexp for both methods validate_valid_name and validate_alpha :
if(!preg_match("/^([-a-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ_-])+$/i", $input[$field]) !== FALSE)
As you can see, the first dash is unseless since it is given at the end of the regexp.
This code
GUMP::add_validator('some_validator', function($field, $input, $param = NULL) {
return array(
'field' => $field,
'value' => $input[$field],
'rule' => 'validate_some_validator',
'param' => $param
);
});
error on line 360 in gump.class.php in latest revision: 5687aac
hello
thanks fot your awesome validation library
if i want to validate a string that contains german characters, should i use use sanitize before that(for converting to utf-8)?or there is no problem for utf-8 strings validation?
thanks
if(is_array($result)) // Validation Failed
{
$this->errors[] = $result;
}
if (!$result) // Validation Failed
{
$this->errors[] = array(
'field' => $field,
'value' => $input[$field],
'rule' => $method,
'param' => $param
);
}
The result is handled in a different matter - the opposite.
I'm trying to create my create your class that extends the GUMP class, but I can't get my FormValidation::vaildate() method working.
I added my own validate method :
require_once('gump.class.php');
class FormValidation extends GUMP
{
public static function validate_alpha_dash_space_apo($field, $input, $param = NULL)
{
if(!isset($input[$field]))
{
return;
}
if(!preg_match("/^([-a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïñðòóôõöùúûüýÿ '-])+$/i", $input[$field]) !== FALSE)
{
return array(
'field' => $field,
'value' => $input[$field],
'rule' => __FUNCTION__
);
}
}
}
The thing is, If I don't copy/paste the gump "validate" method in my own class, I get the following message :
"Fatal error: Uncaught exception 'Exception' with message 'Validator method 'validate_alpha_dash_space_apo' does not exist.' in gump.class.php:150 Stack trace: #0 index.php(129): GUMP::validate(Array, Array) #1 {main} thrown in gump.class.php on line 150 "
My PHP code used to valiate my form is quite simple :
'required',
'firstname' => 'required|alpha_dash_space_apo',
'lastname' => 'required|alpha_dash_space_apo',
);
$valid = FormValidation::validate($_POST, $rules); // This is the line n°129 in index.php pointed by the PHP error message above
```
}
?>
Is there anything more I should do compared to the tutorial on your github page in order to create my own validators ?
Regards
I live in Brazil. How can I show Custom Messages?
The method validate_contains does not check if $input[$field] is set before trying to trim it:
$value = trim(strtolower($input[$field]));
My suggestion to fix it:
$value = isset($input[$field]) ? trim(strtolower($input[$field])) : NULL;
For example:
0.00
1.23
0.10
Cheers.
examples/credit_card.php, line 10 is missing a semicolon. Easy enough to fix locally, but I thought you may want to fix it in the distribution.
Hi,
Thanks For Amazing Library.
for add field name in docs i see this :
GUMP::set_field_name("str", "Street");
for multiple field name GUMP how to work ?!
"str","street"
"tit","title"
and more ....
Thanks For Your time .
The regular expression for the alpha rule looks as follows:
!preg_match("/^([a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ])+$/i", $input[$field]
However, this creates a problem if the field contains spaces, e.g. two words. I had to update the code to include the spaces as valid characters to avoid being given an error. Here is my updated reg ex:
!preg_match("/^([a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ\s])+$/i", $input[$field]
i add this manually and it seems to work?
GUMP::add_filter("whole_number", function($value, $params = NULL) {
return filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
});
great job, cheers!
For example
$a = array('lol' => '8888888');
$r = array('lol' => 'boolean');
$is_valid = GUMP::is_valid($a, $r);
var_dump($is_valid);
returns boolean true
If you're a developer, you'd surely not write your form field name as 'address' or 'full name' as it is. Different by different developer. Say I use 'addr' for address field and 'fname' for First name, and if the fields are incorrect it says 'Addr is required', 'Fname' is required.
Instead, there should be option to give readable 'field name' while defining validators; then I guess even custom error messages won't be required.
The sanitize() function is indiscriminately encoding content to UTF-8. This is a problem when content is already encoded as UTF-8.
The sanitize() function needs some sort of flag for encoding.
Hi,
Fresh git clone and then run:
RUN php custom_validator.php
PHP Fatal error: Call to undefined method GUMP::validate_is_object() in /Users/trav/tm/test/GUMP/gump.class.php on line 360
Cheers,
Trav.
Hi
it would be great to 'humainze' the readable errors by (possibly) setting an array of $field => $field_label so that:
public function get_readable_errors(...) {...
could return the message with a field label, not the field. e.g.:
instead of 'The Name 1 field may only contain alpha-numeric characters'
return 'The Username field may only contain alpha-numeric characters'
and return the array of readable errors ($resp[]) with fields as keys (rather than numeric keys).
yes i could override the function but would rather not as I imagine that function will change as the plugin develops
keep up the great work.
mike
public function checkPasswordStrength($candidate) {
$r1='/[A-Z]/'; //Uppercase
$r2='/[a-z]/'; //lowercase
$r4='/[0-9]/'; //numbers
if(preg_match_all($r1,$candidate, $o)<1) return FALSE;
if(preg_match_all($r2,$candidate, $o)<1) return FALSE;
if(preg_match_all($r3,$candidate, $o)<1) return FALSE;
if(preg_match_all($r4,$candidate, $o)<1) return FALSE;
if(strlen($candidate)<6) return FALSE;
return TRUE;
}
GUMP::add_validator("strong", function($value, $param = NULL) {
return $this->checkPasswordStrength($value);
});
Now my question if strong validator return false i would like to show the error as "You password is not strong,you need to add improve it" how can i do it?
Hello, to validade a DATE 'YYYY-MM-DD' ?
Thanks
Guilherme Viana
Hi, since you are working on a new version, I want to propose alternative shorthand (backwards compatible). This is a bit more semantically readable and allows for filtering. A space can not be used in a field name, so no conflicts writing 'trim username'.
$valid = GUMP::is_valid($_POST,
[
'trim name' => 'required|alpha',
'trim,noise_words bio' => '', // does not produce error, only filters
'pets' => [
'required|exact_len,1|contains,dogs,cats',
'We really need to know if you are a dog person or not.'
]
]);
echo $valid['name']; // already filtered
echo $valid['errors']['fieldname']; // error text
I am trying GUMP on a new project and love it so far, though I use url_exists
which work in most cases but now today I get a non working URL for some reason and it is a valid website as I went on it, you can try it by yourself: http://charts.equityclock.com/
I also call the sanitize on my field $post, but I send the data through JSON anyway and with or without the sanitize doesn't change much in my particular form anyway. How does the url_exists
work exactly?
Please, add to your regexp "alpha, alpha_numeric, etc." ex:
if(!preg_match("/^([a-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ])+$/i", $input[$field]) !== FALSE)
replace to
if(!preg_match("/^([a-z0-9\pL])+$/ui", $input[$field]) !== FALSE)
How do you handle field name keys if the POST request data is in array,
eg: $_POST = ['user']['name], ['user']['email'], ['company']['name], etc
the docs mention that custom validations using GUMP::add_validator should return a boolean. just below this the docs mention extending the class with callable functions but doesn't specify what these functions should return. I'd assumed it would also be boolean but when that didn't work found in GUMP that callable validation functions require a returned array when invalid:
return array( // FAIL VALIDATION -> return array.
'field' => $field,
'value' => $input[$field],
'rule' => __FUNCTION__,
'param' => $param);
perhaps this is stated clearly somewhere (please delete this if it so). But I couldn't find it. may save someone some time.
Thanks for writing this class... It works very well! Could you please provide an example of how to display custom error messages in the event that the validation fails? I'm having trouble figuring out what to do with the array that is returned in this case.
Usually I use an active record class or an ORM to make my queries. E.g. to update the query is something like:
$result = $db->table('posts')->update($update)->where($where);
In this case I have to be sure that the $update
array contains only keys that match table columns, and nothing more.
So I found that you can "whitelist" the submitted data passing an array of allowed keys/columns as 2nd parameter sanitize()
method. All the array keys not included will be ignored and will be not in the sanitized array.
E.g. write the array of allowed fields and sanitize the data:
$_POST = $gump->sanitize($_POST, array('field1', 'field2', 'field3'));
Or you can use the keys of rule or filter arrays if you already declared them:
$rules = array(
'field1' => "required",
'field2' => "required",
);
$_POST = $gump->sanitize($_POST, array_keys($rules));
It's not explained very well in readme and samples. I hope it can help someone.
unsure how to fix, but i thought i'd bring this to your attention:
line 354
if (isset($input[$field])) {
$result = call_user_func(self::$validation_methods[$rule], $field, $input, $param);
$result = $this->$method($field, $input, $param);
if(is_array($result)) // Validation Failed
{
$this->errors[] = $result;
}
}
The example for (creating your own validators)[https://github.com/Wixel/GUMP#creating-your-own-validators-and-filters] explains how to add validators, but there appears to be no way to augment the list of error messages in get_readable_errors
which is not a list at all but a series of strings in a switch block. This means extending GUMP to add validators requires one to stop using get_readable_errors
.
With the exception of length validation messages that switch "characters" and "character" based on number, it looks like all these messages could be stored in an array that could be augmented by subclasses to provide for more error messages. For now I've c/p'd the entire function into my subclass.
Hi,
I am using wordpress with a captcha plugin installed
The plugin function to validate captcha is as below,
<?php if( function_exists( 'cptch_check_custom_form' ) && cptch_check_custom_form() !== true )
echo "Please complete the CAPTCHA."
?>
and the inuput field is generated like this,
<?php if( function_exists( 'cptch_display_captcha_custom' ) ) {
echo "<input type='hidden' name='cntctfrm_contact_action' value='true' />";
echo cptch_display_captcha_custom();
} ?>
is there a way I can make a custom validation to validate the cpatcha filed?
Thanks
It would be nice to be able to validate guids. In particular GUID V4
mysql_real_escape_string this function not working in your sanitize all post values. I want to use mysql_real_escape_string to sanitize all the input for mysql inject attack.
I'm new to github and I didn't find how to pull new requests, so I'm sharing a validator that has been useful to me.
I'm devleopping a new subscription form on my website and want to check if the firstname and lastname are correctly typed in.
For my French website, I need to accept alpha characters, spaces, dashes (but not underscores), apostrophes and accentuated characters
For this, I have created the following method in the gump Class :
protected static function validate_alpha_dash_space_apo($field, $input, $param = NULL)
{
if(!isset($input[$field]))
{
return;
}
if(!preg_match("/^([-a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïñðòóôõöùúûüýÿ '-])+$/i", $input[$field]) !== FALSE)
{
return array(
'field' => $field,
'value' => $input[$field],
'rule' => __FUNCTION__
);
}
}
I hope that will be useful for other people.
Hi,
I'm using your great class for a subscription form on my website.
Everything is working well, but I'm designing french websites and I need to accept accentuated characters for alpha and alpha_numeric validators.
Here are my own versions of the default gump validators :
protected static function validate_alpha($field, $input, $param = NULL)
{
if(!isset($input[$field]))
{
return;
}
if(!preg_match("/^([a-zÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ])+$/i", $input[$field]) !== FALSE)
{
return array(
'field' => $field,
'value' => $input[$field],
'rule' => __FUNCTION__
);
}
}
/**
* Determine if the provided value contains only alpha-numeric characters
*
* @static
* @access protected
* @param string $field
* @param array $input
* @return mixed
*/
protected static function validate_alpha_numeric($field, $input, $param = NULL)
{
if(!isset($input[$field]))
{
return;
}
if(!preg_match("/^([a-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ])+$/i", $input[$field]) !== FALSE)
{
return array(
'field' => $field,
'value' => $input[$field],
'rule' => __FUNCTION__
);
}
}
/**
* Determine if the provided value contains only alpha characters with dashed and underscores
*
* @static
* @access protected
* @param string $field
* @param array $input
* @return mixed
*/
protected static function validate_alpha_dash($field, $input, $param = NULL)
{
if(!isset($input[$field]))
{
return;
}
if(!preg_match("/^([-a-z0-9ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ_-])+$/i", $input[$field]) !== FALSE)
{
return array(
'field' => $field,
'value' => $input[$field],
'rule' => __FUNCTION__
);
}
}
In short, I have just added in the regular expressions the following string : "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïñðòóôõöùúûüýÿ"
The affected methods are : validate_alpha, validate_alpha_numeric and validate_alpha_dash.
Note that this change would be useful for Spanish websites as well as for some other euroopean languages.
Regards,
Ben.
I have tested multiple validate functions with the string value '0' and integer 0 which evaluates to true in the empty() function. I checked the docs which states:
Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.
Noticed this when using validate_required and passing a zero - which, for this function, failed when it should have passed.
Most likely it will not be a big security concern, but will give false results which can lead to bugs. Most of the validators use the same check for empty values, also mine as I more or less copied it from the others. The workaround I'm using for a couple of these, are:
protected function validate_required($field, $input, $param = NULL)
{
if(isset($input[$field]) && (!empty($input[$field]) || is_numeric($input[$field])))
protected function validate_max_numeric($field, $input, $param = null)
{
if (!isset($input[$field]) || (empty($input[$field]) && !is_numeric($input[$field]))) {
Would like to get a second opinion on this, thanks!
Nice PHP tool for verifying HTML forms or other objects! Only, in my opinion a field which is not required and is empty, should not be checked for any other rules. Therefore, I added the following IF statement in function validate():
public function validate(array $input, array $ruleset)
{
...
$rules = explode('|', $rules);
/*
* Only perform all checks if the field is required or not empty
*/
if ( in_array("required", $rules) || (isset($input[$field]) && trim($input[$field]) != '') )
{
foreach($rules as $rule)
{
...
}
}
}
return (count($this->errors) > 0)? $this->errors : TRUE;
}
Maybe this change can be added to the version in the repository.
Regards,
Frans
Great script. I've been looking for a good form validation class for a while.
A couple of suggestions:
Great work!
Is this by design, or a bug?
Our '$_POST' is nested, is it possible to use GUMP to access variables on second levels?
Like this?
'contact.number' => 'required|alpha_numeric',
'contact>number' => 'required|alpha_numeric',
'contact' => array("number" => 'required|alpha_numeric'),
There is no docs covering this, seems strange to not have implemented support.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.