Validate lowercase input by user - php

Using this code which works fine if the user enters all capital letters. However, I need to automatically accept lowercase and sentence case as valid inputs by the user. Currently, this doesnt work, any ideas?
add_filter( 'gform_field_validation_17_4', 'custom_validation', 10, 4 );
function custom_validation( $result, $value, $form, $field ) {
$arrWhitelist = array('KNITS10', 'KATNA20');
if ( $result['is_valid'] && !in_array( $value, $arrWhitelist )) {
$result['is_valid'] = false;
$result['message'] = 'Incorrect code';
}
return $result;
}

use strtoupper(), to make the users input match yours:
add_filter( 'gform_field_validation_17_4', 'custom_validation', 10, 4 );
function custom_validation( $result, $value, $form, $field ) {
$arrWhitelist = array('KNITS10', 'KATNA20');
if ( $result['is_valid'] && !in_array( strtoupper($value), $arrWhitelist )) {
$result['is_valid'] = false;
$result['message'] = 'Incorrect code';
}
return $result;
}

You could also use strcasecmp(), but the cleaner option in this scenario would be strtoupper.
The resulting code using strcasecmp would be:
function custom_validation($result, $value, $form, $field)
{
$arrWhitelist = array('KNITS10', 'KATNA20');
array_walk(
$arrWhitelist, function ($item) use ($value, $result) {
if (strcasecmp($item, $value) === 0) {
$result['is_valid'] = false;
$result['message'] = 'Incorrect code';
}
}
);
return $result;
}

Related

can't target gravityform input or field ID in filter

I have a filter/validation script that only accepts emails from a certain domain. This is working pretty good but I need to have it on a specific from input ID:
As per https://docs.gravityforms.com/gform_field_validation/#11-email-validation-by-third-party-api#usage :
You can also target a specific field by adding the form id and field
id after the hook name.
//The following declaration targets field 1 in form 6 add_filter(
'gform_field_validation_6_1', 'your_function_name', 10, 4 );
Currently my code looks like this:
add_filter( 'gform_field_validation', function ( $result, $value, $form, $field ) {
if ( ! $result['is_valid'] && $field->get_input_type() === 'email' && strpos($field->get_field_input(), 'company.com') === true) {
$result['is_valid'] = true;
$result['message'] = '';
} else {
$result['is_valid'] = false;
$result['message'] = 'E-Mail must be a company.com address';
}
return $result;
}, 10, 4 );
My form and input IDs are confirmed as 1 and 13, respectively:
When I change the code to the following, the script stops working:
add_filter( 'gform_field_validation_13_1', function ( $result, $value, $form, $field ) {
if ( ! $result['is_valid'] && $field->get_input_type() === 'email' && strpos($field->get_field_input(), 'company.com') === true) {
$result['is_valid'] = true;
$result['message'] = '';
} else {
$result['is_valid'] = false;
$result['message'] = 'E-Mail must be a company.com address';
}
return $result;
}, 10, 4 );
Is there another way I need to check my form ID? What is missing here?
From the documentation gform_field_validation_6_1 means that it targets field 1 in form 6.
You form id is 1 and input field id is 13 so the filter should be gform_field_validation_1_13.

How can I show dynamic error message using PHP?

I have a html form and this form is validating by PHP with jQuery/Ajax request.
Currently it's working perfectly. Now I want to show a dynamic error message.
For e. g:
I am validating integer number using following function :
function only_number ($string) {
if( preg_match('/^[0-9]+$/', $string ) ) {
return true;
} else {
return false;
}
}
This function is implementing by following way :
$msg = array();
$msg['error'] = false;
if(empty($emp_id)) {
$msg[] = 'Select assign to';
$msg['error'] = true;
} elseif( only_number($emp_id) === false ) {
$msg[] = 'Assign to must be numeric value';
$msg['error'] = true;
}
echo json_encode($msg);
You see that I am showing error message
Assign to must be numeric value
in the function implemented page e.g. update.php
It's very time consuming that I need to type several type of error message every time.
NOW, I want to write this error message in the function and it will show/implemented on validating page like : update.php page.
How can I do this ?
You can return array from your function. E.g:
function only_number ($string) {
$result = array(
'success' => false,
'error' => '',
);
if( preg_match('/^[0-9]+$/', $string ) ) {
$result['success'] = true;
} else {
$result['error'] = 'Assign to must be numeric value';
}
return $result;
}
And check:
if (empty($emp_id)) {
$msg[] = 'Select assign to';
$msg['error'] = true;
} else {
$check = only_number($emp_id);
if ($check['success'] == false) {
$msg[] = $check['error'];
$msg['error'] = true;
}
}
In stead of returning true/false you can also return a string with the error message
function only_number ($string) {
if (empty ($string) return 'Select assign to';
if(!preg_match('/^[0-9]+$/', $string ) ) return 'Assign to must be numeric value';
else return 'no error';
}
next in your code
if (only_number($emp_id) <> 'no error') echo (json_encode(only_number($emp_id)));

OO way or functional way of string comparison conditionals in php

I am curling on a specific page that returns only html. To determine what page it returns, I simply try to stripos the result of the curl
Like so:
$result = curl_exec($ch);
if(stripos($result, 'success') !== false) {
// do something
} else {
if (stripos($result, 'foo') !== false) {
// do something
} else if (stripos($result, 'foo') !== false) {
// do something
} else if (stripos($result, 'bar') !== false) {
// do something
} else if (stripos($result, 'bazz') !== false) {
// do something
} else {
// do something
}
}
This is quite messy I think, is there an OO way or functional way to solve this kind of problem if I were looking at minimal if statements or ultimately an if-less code.
What you are searching for a ways of abstraction. In this example you are repeating yourself in case analysis and this might be the best approach if the "do something" is very different and not consistent.
$map = [ 'success' => function () { return 1; },
'foo' => function () { return 2; },
'bar' => function () { return 3; },
'bazz' => function () { return 4; } ];
foreach ( $map as $search => $value )
{
if (stripos($result, $search) !== false )
{
return call_user_func($value);
}
}
In my example these could just have been constants and we could just return them instead of applying a function. In a functional pattern this would be like the function any in Scheme SRFI-1 except it returns it's true value:
// This function uses PHP 5.6 ellipsis
function array_any(callable $callable, ...$arrays) {
if( count($arrays) == 1 ) {
$args_zipped = array_map( function ($x) { return [$x]; }, $arrays[0]);
} else {
array_unshift( $arrays, null);
$args_zipped = call_user_func_array( "array_map", $arrays);
}
foreach ( $args_zipped as $args ) {
$result = call_user_func_array($callable, $args);
if( $result !== false )
return $result;
}
return false;
}
array_any( function ($search, $value) {
if ( stripos($result, $search) !== false )
return $value;
return false;
},
array_keys($map),
array_values($map));
The function in itself uses linear update, but as you can see it works similar to array_map.
This simple function would do that work:
function checkWord ($haystack,$needle){
foreach ($needle as $word) {
if (stripos($haystack, $word) !== false) {
echo $word." was found!<br/>";
}
else{
echo $word." wasn't found<br/>";
}
}
}
checkWord("Hello what's up?",array('Hello','Huhud','up','?'));
This will output:-
Hello was found!
Huhud wasn't found
up was found!
? was found!

how aright use function with echo and return?

Code ONE (WORK ARIGHT):
function Hello( $rel ) {
$res = mysqli("SELECT * FROM TABLE");
$result = $res->num_rows;
if ( $rel == 1 ) {
print $result;
} elseif ( $rel == 2 ) {
echo $result;
} elseif ( $rel == 3 ) {
return $result;
} else {
return $result;
}
}
$pr = HELLO(3);
echo $pr;
It code work aright.
Then I wanted to do one function to process the data and output the result.
Code:
function out( $rel, $result ) {
if ( $rel == 1 ) {
print $result;
} elseif ( $rel == 2 ) {
echo $result;
} elseif ( $rel == 3 ) {
return $result;
} else {
return $result;
}
}
function Hello( $rel ) {
$res = mysqli("SELECT * FROM TABLE");
$result = $res->num_rows;
out( $rel, $result )
}
$pr = HELLO(3);
echo $pr;
But now code not work(not show results on line echo $pr;)...
Tell me please why i have error and how write aright?
P.S.: i not know that need use return before function.
Thanks all for my new knowledge.
You simply forgot to add return to out($rel,$result)
as it is right now, your Hello() function doesn't have return value.
You have not return the value in the second code.
you need to use like this:
return out($rel,$result).
The return is in the second function, second function returns the value to function first, now function first also needs to return, so u need to add return there too.

PHP - Validation function to return true|false, AND a message if false

I have a validation function which returns either true or false.
However, I want it to provide info as to what the problem is, when there is one.
Let's say the function is like this:
function is_valid($val) {
$result = true;
if( rule_1_not_met ) $result = false;
if( rule_2_not_met ) $result = false;
return $result;
}
Which is used like this
$val = $_GET['some_param'];
if(!is_valid($val)) $out .= 'Not so helpful feedback.';
...
I thought I could change it like this:
function is_valid($val) {
$result = array(true, array());
if( rule_1_not_met ) $result[1][] = 'Reason 1';
if( rule_2_not_met ) $result[1][] = 'Reason 2';
if(count($result[1]) > 0) $result[0] = false;
return $result;
}
And use it like this:
$val = $_GET['some_param'];
$validation_result = is_valid($val);
if(!$validation_result[0]) $out .= implode('<br/>', $validation_result[1]);
...
My question is
Am I in, for unexpected results with this?
Are there better ways to achieve this?
P.S. Would make this community wiki
You are in the right track but I would like to do this in this way
function is_valid($val,&$mes) {
$result = true;
if( rule_1_not_met ) { $mes[]='message one'; $result = false; }
if( rule_2_not_met ) { $mes[]='Message two'; $result = false; }
return $result;
}
$mes=array();
if(isvalid($val,$mes) ===false) $out .= implode('<br/>', $mes);
In my opinion, your proposed solution works fine. The only problem with it is that you have to remember that $validation_result[0] is the status and $validation_result[1] contains the messages. This might be OK with you but it will be hard to maintain if other people use your code. One thing you can do is when you call your function, you can use array destructuring to at least store the results with meaningful variable names. For example:
[$valid, $errors] = is_valid($val);
if(!$valid) $out .= implode('<br/>', $errors);
For the reason mentioned above, I like Brad Thomas's solution of creating a specialized class that contains the messages and status. Since the properties are named, you don't have to guess how to access the validation information. Also, most good IDEs will autocomplete when you try to access their properties.
I also have an alternate solution. Instead of including a boolean true or false. Just return the array of messages. The caller would just have to check if the returned array has a non-zero number of errors. Here is an example:
function get_errors($val) {
$errors = array();
if( rule_1_not_met ) $errors[] = 'Reason 1';
if( rule_2_not_met ) $errors[] = 'Reason 2';
return $errors;
}
Then the caller would use it like this:
$val = $_GET['some_param'];
$validation_result = get_errors($val);
if (count($validation_result) > 0) $out .= implode('<br/>', $validation_result);
You could use a Result object that encapsulates return data, a message and a status.
i.e.
class Result( $bResult, $sMessage, $mData ) {
public function __construct() {
$this->bResult = $bResult;
$this->sMessage = $sMessage;
$this->mData = $mData;
}
}
In Your code:
$result = new Result(true, 'some helpful message here', null);
$reasons = array();
function is_valid($val)
{
global $reasons;
if ( rule_1_not_met ) $reasons[] = 'Reason 1';
if ( rule_2_not_met ) $reasons[] = 'Reason 2';
if ( count($reasons) == 0 )
return TRUE;
else
return FALSE;
}
if (!is_valid($condition))
{
echo 'Was not valid for these reasons<br />';
foreach($reasons as $reason)
echo $reason, '<br>';
}
else
echo 'Is valid!';
This question is old, and makes a showcase of bad and outdated practices. Using global is frowned upon, and using references in this context is just the same.
Only Cave Johnson's answer makes it straight, but still the usage could be confusing. A better solution would be to write a class, but not as silly one as in the Brad Thomas's answer.
class NumberValidator
{
protected $errors;
public function validate($number)
{
if(!is_numeric($number))
{
$this->errors[] = "The value provided is not numeric";
return false;
}
if($number < 10)
{
$this->errors[] = "The number is less than 10";
return false;
}
return true;
}
public function getErrors()
{
return $this->errors;
}
}
and then it can be used like this
$validator = new NumberValidator();
if($validator->validate($number)) {
/*success*/
}
and then $validator->getErrors() can be used elsewhere

Categories