GithubHelp home page GithubHelp logo

wixel / gump Goto Github PK

View Code? Open in Web Editor NEW
1.2K 84.0 342.0 828 KB

A fast, extensible & stand-alone PHP input validation class that allows you to validate any data

Home Page: https://wixelhq.com

License: MIT License

PHP 99.18% Dockerfile 0.27% Shell 0.55%

gump's Introduction

Getting started

GUMP is a standalone PHP data validation and filtering class that makes validating any data easy and painless without the reliance on a framework. GUMP is open-source since 2013.

Supports wide range of PHP versions (php7.1 to php8.3) and ZERO dependencies!

Total Downloads Latest Stable Version Build Status Coverage Status License

Install with composer

composer require wixel/gump

Short format example for validations

$is_valid = GUMP::is_valid(array_merge($_POST, $_FILES), [
    'username'       => 'required|alpha_numeric',
    'password'       => 'required|between_len,4;100',
    'avatar'         => 'required_file|extension,png;jpg',
    'tags'           => 'required|alpha_numeric', // ['value1', 'value3']
    'person.name'    => 'required',               // ['person' => ['name' => 'value']]
    'persons.*.age'  => 'required'                // ['persons' => [
                                                  //      ['name' => 'value1', 'age' => 20],
                                                  //      ['name' => 'value2']
                                                  // ]]
]);

// 1st array is rules definition, 2nd is field-rule specific error messages (optional)
$is_valid = GUMP::is_valid(array_merge($_POST, $_FILES), [
    'username' => ['required', 'alpha_numeric'],
    'password' => ['required', 'between_len' => [6, 100]],
    'avatar'   => ['required_file', 'extension' => ['png', 'jpg']]
], [
    'username' => ['required' => 'Fill the Username field please.'],
    'password' => ['between_len' => '{field} must be between {param[0]} and {param[1]} characters.'],
    'avatar'   => ['extension' => 'Valid extensions for avatar are: {param}'] // "png, jpg"
]);

if ($is_valid === true) {
    // continue
} else {
    var_dump($is_valid); // array of error messages
}

Short format example for filtering

$filtered = GUMP::filter_input([
    'field'       => ' text ',
    'other_field' => 'Cool Title'
], [
    'field'       => ['trim', 'upper_case'],
    'other_field' => 'slug'
]);

var_dump($filtered['field']); // result: "TEXT"
var_dump($filtered['other_field']); // result: "cool-title"

Long format example

$gump = new GUMP();

// set validation rules
$gump->validation_rules([
    'username'    => 'required|alpha_numeric|max_len,100|min_len,6',
    'password'    => 'required|max_len,100|min_len,6',
    'email'       => 'required|valid_email',
    'gender'      => 'required|exact_len,1|contains,m;f',
    'credit_card' => 'required|valid_cc'
]);

// set field-rule specific error messages
$gump->set_fields_error_messages([
    'username'      => ['required' => 'Fill the Username field please, its required.'],
    'credit_card'   => ['extension' => 'Please enter a valid credit card.']
]);

// set filter rules
$gump->filter_rules([
    'username' => 'trim|sanitize_string',
    'password' => 'trim',
    'email'    => 'trim|sanitize_email',
    'gender'   => 'trim',
    'bio'      => 'noise_words'
]);

// on success: returns array with same input structure, but after filters have run
// on error: returns false
$valid_data = $gump->run($_POST);

if ($gump->errors()) {
    var_dump($gump->get_readable_errors()); // ['Field <span class="gump-field">Somefield</span> is required.'] 
    // or
    var_dump($gump->get_errors_array()); // ['field' => 'Field Somefield is required']
} else {
    var_dump($valid_data);
}

⭐ Available Validators

Important: If you use Pipe or Semicolon as parameter value, you must use array format.

$is_valid = GUMP::is_valid(array_merge($_POST, $_FILES), [
    'field' => 'regex,/partOf;my|Regex/', // NO
    'field' => ['regex' => '/partOf;my|Regex/'] // YES
]);
Rule Description
required Ensures the specified key value exists and is not empty (not null, not empty string, not empty array).
contains,one;two;use array format if one of the values contains semicolons Verify that a value is contained within the pre-defined value set.
contains_list,value1;value2 Verify that a value is contained within the pre-defined value set. Error message will NOT show the list of possible values.
doesnt_contain_list,value1;value2 Verify that a value is contained within the pre-defined value set. Error message will NOT show the list of possible values.
boolean,strict Determine if the provided value is a valid boolean. Returns true for: yes/no, on/off, 1/0, true/false. In strict mode (optional) only true/false will be valid which you can combine with boolean filter.
valid_email Determine if the provided email has valid format.
max_len,240 Determine if the provided value length is less or equal to a specific value.
min_len,4 Determine if the provided value length is more or equal to a specific value.
exact_len,5 Determine if the provided value length matches a specific value.
between_len,3;11 Determine if the provided value length is between min and max values.
alpha Determine if the provided value contains only alpha characters.
alpha_numeric Determine if the provided value contains only alpha-numeric characters.
alpha_dash Determine if the provided value contains only alpha characters with dashed and underscores.
alpha_numeric_dash Determine if the provided value contains only alpha numeric characters with dashed and underscores.
alpha_numeric_space Determine if the provided value contains only alpha numeric characters with spaces.
alpha_space Determine if the provided value contains only alpha characters with spaces.
numeric Determine if the provided value is a valid number or numeric string.
integer Determine if the provided value is a valid integer.
float Determine if the provided value is a valid float.
valid_url Determine if the provided value is a valid URL.
url_exists Determine if a URL exists & is accessible.
valid_ip Determine if the provided value is a valid IP address.
valid_ipv4 Determine if the provided value is a valid IPv4 address.
valid_ipv6 Determine if the provided value is a valid IPv6 address.
valid_cc Determine if the input is a valid credit card number.
valid_name Determine if the input is a valid human name.
street_address Determine if the provided input is likely to be a street address using weak detection.
iban Determine if the provided value is a valid IBAN.
date,d/m/Y Determine if the provided input is a valid date (ISO 8601) or specify a custom format (optional).
min_age,18 Determine if the provided input meets age requirement (ISO 8601). Input should be a date (Y-m-d).
max_numeric,50 Determine if the provided numeric value is lower or equal to a specific value.
min_numeric,1 Determine if the provided numeric value is higher or equal to a specific value.
starts,Z Determine if the provided value starts with param.
required_file Determine if the file was successfully uploaded.
extension,png;jpg;gif Check the uploaded file for extension. Doesn't check mime-type yet.
equalsfield,other_field_name Determine if the provided field value equals current field value.
guidv4 Determine if the provided field value is a valid GUID (v4)
phone_number Determine if the provided value is a valid phone number.
regex,/test-[0-9]{3}/ Custom regex validator.
valid_json_string Determine if the provided value is a valid JSON string.
valid_array_size_greater,1 Check if an input is an array and if the size is more or equal to a specific value.
valid_array_size_lesser,1 Check if an input is an array and if the size is less or equal to a specific value.
valid_array_size_equal,1 Check if an input is an array and if the size is equal to a specific value.

⭐ Available Filters

Filter rules can also be any PHP native function (e.g.: trim).

Filter Description
noise_words Replace noise words in a string (http://tax.cchgroup.com/help/Avoiding_noise_words_in_your_search.htm).
rmpunctuation Remove all known punctuation from a string.
urlencode Sanitize the string by urlencoding characters.
htmlencode Sanitize the string by converting HTML characters to their HTML entities.
sanitize_email Sanitize the string by removing illegal characters from emails.
sanitize_numbers Sanitize the string by removing illegal characters from numbers.
sanitize_floats Sanitize the string by removing illegal characters from float numbers.
sanitize_string Sanitize the string by removing any script tags.
boolean Converts ['1', 1, 'true', true, 'yes', 'on'] to true, anything else is false ('on' is useful for form checkboxes).
basic_tags Filter out all HTML tags except the defined basic tags.
whole_number Convert the provided numeric value to a whole number.
ms_word_characters Convert MS Word special characters to web safe characters. ([“ ”] => ", [‘ ’] => ', [–] => -, […] => ...)
lower_case Converts to lowercase.
upper_case Converts to uppercase.
slug Converts value to url-web-slugs.
trim Remove spaces from the beginning and end of strings (PHP).

Other Available Methods

/**
 * Setting up the language, see available languages in "lang" directory
 */
$gump = new GUMP('en');

/**
 * This is the most flexible validation "executer" because of it's return errors format.
 *
 * Returns bool true when no errors.
 * Returns array of errors with detailed info. which you can then use with your own helpers.
 * (field name, input value, rule that failed and it's parameters).
 */
$gump->validate(array $input, array $ruleset);

/**
 * Filters input data according to the provided filterset
 *
 * Returns array with same input structure but after filters have been applied.
 */
$gump->filter(array $input, array $filterset);

// Sanitizes data and converts strings to UTF-8 (if available), optionally according to the provided field whitelist
$gump->sanitize(array $input, $whitelist = null);

// Override field names in error messages
GUMP::set_field_name('str', 'Street');
GUMP::set_field_names([
    'str' => 'Street',
    'zip' => 'ZIP Code'
]);

// Set custom error messages for rules.
GUMP::set_error_message('required', '{field} is required.');
GUMP::set_error_messages([
    'required'    => '{field} is required.',
    'valid_email' => '{field} must be a valid email.'
]);

Creating your own validators and filters

Adding custom validators and filters is made easy by using callback functions.

/**
 * You would call it like 'equals_string,someString'
 *
 * @param string $field  Field name
 * @param array  $input  Whole input data
 * @param array  $params Rule parameters. This is usually empty array by default if rule does not have parameters.
 * @param mixed  $value  Value.
 *                       In case of an array ['value1', 'value2'] would return one single value.
 *                       If you want to get the array itself use $input[$field].
 *
 * @return bool   true or false whether the validation was successful or not
 */
GUMP::add_validator("equals_string", function($field, array $input, array $params, $value) {
    return $value === $params;
}, 'Field {field} does not equal to {param}.');

// You might want to check whether a validator exists first
GUMP::has_validator($rule);

/**
 * @param string $value Value
 * @param array  $param Filter parameters (optional)
 *
 * @return mixed  result of filtered value
 */
GUMP::add_filter("upper", function($value, array $params = []) {
    return strtoupper($value);
});

// You might want to check whether a filter exists first
GUMP::has_filter($rule);

Alternately, you can simply create your own class that extends GUMP. You only have to have in mind:

  • For filter methods, prepend the method name with "filter_".
  • For validator methods, prepend the method name with "validate_".
class MyClass extends GUMP
{
    protected function filter_myfilter($value, array $params = [])
    {
        return strtoupper($value);
    }

    protected function validate_myvalidator($field, array $input, array $params = [], $value)
    {
        return $input[$field] === 'good_value';
    }
}

$validator = new MyClass();
$validated = $validator->validate($_POST, $rules);

Global configuration

This configuration values allows you to change default rules delimiters (e.g.: required|contains,value1;value2 to required|contains:value1,value2).

GUMP::$rules_delimiter = '|';

GUMP::$rules_parameters_delimiter = ',';

GUMP::$rules_parameters_arrays_delimiter = ';';

gump's People

Contributors

absherzad avatar adaniello avatar cjrupak avatar davidmars avatar eko3alpha avatar filisko avatar flaversaver avatar groucho75 avatar headzoo avatar ib4 avatar idofri avatar innovaweb-dev avatar joseluisq avatar marios88 avatar mazubieta avatar nicklozon avatar phatnt93 avatar pl4g4 avatar rcrowe avatar redian avatar roydekleijn avatar rwitchell avatar ryanhalliday avatar saphilc avatar scottcase avatar sn avatar stephenneate avatar tty02-fl avatar tylerjaynelson avatar uacode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gump's Issues

error when add validator

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

docs don't mention that custom validators should return array if invalid

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.

whole number would be great

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!

url_exists fail on a valid URL

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?

Custom Field names in Readable errors

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.

Notice in method validate_contains

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; 

Sanitize indiscriminately encodes content

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.

whitelist sanitization broken

$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

Using only isset() and empty() function slips the value zero through validators

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!

sanitize() 2nd parameter is useful for active record or ORM

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.

Validation by alpha fails if the field contains spaces

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]

Nested Post request data?

How do you handle field name keys if the POST request data is in array,
eg: $_POST = ['user']['name], ['user']['email'], ['company']['name], etc

No checks for empty non-required fields

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

mysql_real_escape_string

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.

customize readable errors

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

$result overwritten immediately

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;
    }
}

Small mistake in the regexp for validate_alpha_dash and validate_valid_name

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.

custom validator error

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.

Ipv4 vs IPv6

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.

trigger error on too many POST fields

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

Validator method '$method' does not exist.

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

Error Handling Example

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.

Validating Captcha

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

How to add custom validation funcation error text

public function checkPasswordStrength($candidate) {
$r1='/[A-Z]/'; //Uppercase
$r2='/[a-z]/'; //lowercase
$r3='/[!@#$%^&*()-_=+{};:,<.>]/'; // whatever you mean by 'special char'
$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?

Parse error: syntax error, unexpected '"'

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 !

No way to augment readable_errors

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.

Quotes on validate_valid_name method

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.

replace multiple field name

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 .

Multi-Dimensional or Nested Arrays?

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.

Boolean validation does not work properly.

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"...

please, add support cyrillic

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)

what about a "name" validator ?

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.

Alternative shorthand syntax

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

Php notices

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 !

Special characters (accents) not managed in alpha & alpha_numeric validators

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.

Outdated documentation

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?

The result of validators added using add_validator() method not handled correctly.

  1. Handling a validator which is a member of the class:
    $result = $this->$method($field, $input, $param);

if(is_array($result)) // Validation Failed
{
$this->errors[] = $result;
}

  1. Handling of validators via add_validator() method:
    $result = call_user_func(self::$validation_methods[$rule], $field, $input, $param);

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.

Custom Form Validation

Great script. I've been looking for a good form validation class for a while.

A couple of suggestions:

  1. I want to be able to easily output error messages next to the form field(s) that have caused the error. It would be nice if the script could return a multidimensional array with the field name as the key. E.g. $returnarray['fieldname'] = array("Formatted Error Message 1", Formated Error Message 2", etc.). That way, I can quickly do a count to see if the field has produced an error, and then loop through the array to display the error messages for that field.
  2. Where character lengths are not the right length, it would be good to include the inputted length in the error message (e.g. "You cannot use more than 12 characters. You have entered 8 characters"). Granted I could append this manually, but would be nice as a built in variable.

Great work!

max_len poorly worded

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;

UTF-8 strings validation

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.