return message if input is in array - php

I have a form validation that, so far, returns an error message if either of two defined words/phrase are present in the input area:
add_filter('gform_validation_3', 'custom_validation');
function custom_validation($validation_result){
$form = $validation_result["form"];
foreach($form['fields'] as &$field){
/* Check that the value of the field that was submitted. e.g. the name="input_1" that is generated by Gravity Forms */
if($_POST['input_4'] == "Your First Name" || "SEO"){
// set the form validation to false
$validation_result["is_valid"] = false;
//The field ID can be found by hovering over the field in the backend of WordPress
if($field["id"] == "4"){
$field["failed_validation"] = true;
$field["validation_message"] = "This field needs to be your actual first name.";
}
}
}
//Assign modified $form object back to the validation result
$validation_result["form"] = $form;
return $validation_result;
}
I'm not sure now how to create an array to define the words that are not allowed, so that I can have a much longer list?

First of all, the first "if" is incorrect, I think you meant:
if($_POST['input_4'] == "Your First Name" || $_POST['input_4'] =="SEO")
A good way to achieve what you long is:
$forbidden_words = ["Your First Name", "SEO"];
$is_valid = !in_array($_POST['input_4'], $forbidden_words); //false if the word is in array
After that you may go:
if($is_valid)
//do magic

You can use function in_array()
<?php
$blacklisted = ['some', 'ugly', 'bad', 'words'];
if(in_array('ugly', $blacklisted)){
echo('bad word spotted');
}
demo: https://repl.it/#kallefrombosnia/DarkvioletDeepPolygons

Related

Form validation for multiple text input Codeigniter

Array values in form are always a problem for form validation in CI. Now I've to input multiple values and those array values are to be stored in DB. Now the user can keep some fields blanks by mistake as shown below in the links:
Input values.
Values in the array on submission.
I used this tutorial to add input boxes on + button click. On submission the blank values will be truncated and then not null array values will added to database. I tried this using a sample program in native PHP but could not implement it in CI.
I used the following code in native PHP to insert values in DB truncating null values:
<?php
include 'sql_connect.php';
$str = array();
for($i=0;$i<count($_POST["txtSiteName"]);$i++)
{
$str[] = $_POST["txtSiteName"][$i];
}
$str = array_filter($str, function($item) {if(!is_null($item)) return $item;});
foreach($str as $loop_str)
{
$arr_str[] = $loop_str;
}
for($k = 0; $k<count($arr_str);$k++)
{
mysql_query("INSERT INTO sitename (name) VALUES ('".$arr_str[$k]."')") or die(mysql_error());
}
print_r($arr_str);
?>
How can I achieve this in CI ?
I tried to use callback function but the array value is not being passed to the callback function.
EDIT:
The below code shows my callback function :
On entering 3 urls it is called 3 times. Is that normal ?
Also my array_walk's callback function is not working. Calling a callback function inside another callback function is not possible ?
public function null_check()
{
$urls = $this->input->post('link_name');
array_walk($urls, 'prepurl');
var_dump($urls);
}
prepurl function:
public function prepurl($item, $key)
{
$item = "http://".$item;
}
Your question is not clear to me but since you mentioned to validate multiple text boxes. So if your text boxes are something like this
<input type="text" name="txtSiteName[]" />
<input type="text" name="txtSiteName[]" />
then simply you can use
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'required|xss_clean');
to validate all the text boxes against null or empty.
Update (TO pass an argument in to the callback)
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'callback_sitename_check[' . $this->input->post('txtSiteName') . ']');
function sitename_check($str, $sitenames) {
// $sitenames will be your textboxe's array
}
The first argument is used by CodeIgniter by default so second argument is your parameter. Also take a look at insert_batch() to insert multiple records.
Also you can do this like
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'callback_sitename_check');
function sitename_check() {
$sitenames = $this->input->post('txtSiteName');
}
Update: (For array_walk)
array_walk($urls, array($this, 'prepurl'));
Here is a simple process of doing it
Set message like this
$this->form_validation->set_rules('txtSiteName[]', 'Site Name', 'required|xss_clean|callback_check_array');
Here is callback
function check_array()
{
$txtSiteName = $this->input->post('txtSiteName');
$error = 0;
foreach($txtSiteName as $key => $value)
{
if(!empty($value)){
$error = $error + 1;
}
}
if($error == 0){
return TRUE;
}else{
$this->form_validation->set_message('check_array', 'All fields are empty. Please provide at leaset 1');
return FALSE;
}
}
When validation is successfull run this code or modify according to your requirements
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$txtSiteName = $this->input->post('txtSiteName');
foreach($txtSiteName as $key => $value)
{
if(!empty($value)){
$data['name'] = $value;
$this->mymodel->insert($data);
}
}
}
Model Method
function insert($data)
{
$this-db->insert('table_name',$data);
}

PHP conditional statment inside a function

I am trying to create function that takes two arguments one for the user input and the other a message for error. I initially have an associative array with the two input fields and the corresponding error.
When the function is submitted without any entry I get two similar output; I thought I would get 'test1' and 'test2'. I am passing different arguments each time but I get the same result. The code is below
$valid = TRUE;
//$errors='';
$errors=array('desc_error'=>'please enter valid description',
'title_error'=>'provide valid title','no_error'=>'',);
function sanitizeText($input,$error){
//$input;
if($input!='')
{
$input= filter_var($input, FILTER_SANITIZE_STRING);
if($input==''){
global $errors;
$errors[$error];
$valid=FALSE;
return $errors[$error];
}
else{
$input;
echo 'test 1';
return $input;
}
}
else if($input=='')
{
if($input==$_POST['desc'])
{
echo 'the description field is required<br/>';
$valid=FALSE;
}
else{
//
}
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText($_POST['title'],'title_error');
$desc=sanitizeText($_POST['desc'],'desc_error');
}
?>
<form method="post" action="">
<p>Book Title:<input type="text" name="title" maxlength="100" value=""/></p>
<p>Desc:<input type="text" name="desc" maxlength="100" value=""/></p>
<p><input type="submit" name="submit" value="Submit"/></p>
</form>
I think you are trying to validate form using php you can also user javascript to validate but to do it using php please refer following links.
http://myphpform.com/required-optional-fields.php
http://coredogs.com/lesson/form-and-php-validation-one-page
http://www.phpf1.com/tutorial/php-form.html?page=3
and
http://www.montanaprogrammer.com/php-web-programming/php-form-validation/
Your code does not make sense logic wise. Firstly, you check if $input is an empty string, or is not, and then within that first check.. you again make the same exact check. Since ifs are evaluated in order, and input is not ever going to be an empty string, the first if will always execute.
Then, your first 'else'; it will only execute if the $input variable is an empty string.. I can sort of see what you're attempting to do, but it won't work as it is right now. In order for it to work, it would have to look something like the below:
function sanitizeText($input,$error) {
global $errors;
global $valid;
$input_val = filter_var($_POST[$input], FILTER_SANITIZE_STRING);
if ($input_val != '') {
$valid = TRUE;
return $input;
}
else if ($input_val == '') {
$valid = FALSE;
echo $errors[$error].'<br />';
}
}
if(isset($_POST['submit']))
{
$title=sanitizeText('title','title_error');
$desc=sanitizeText('desc','desc_error');
}
If the input value is not an empty string, it will return the input value. If it is, it will not return anything and will instead echo the appropriate error.

Custom Zend Validator

I want to create a custom validator in Zend.
for e.g. my code:
$txt_state = new Zend_Form_Element_Text('state');
$txt_state->setLabel('State');
$txt_prop = new Zend_Form_Element_Text('pin');
$txt_prop->setLabel('Property');
Now I want that the form must be submitted only if at least one of these 2 elements are not empty.
you can do it dirty way like this:
if ($this->getRequest()->isPost()) {
if (is_empty($form->getElement('state')->getValue())) {
$form->getElement('pin')->setRequired();
}
if (is_empty($form->getElement('pin')->getValue())) {
$form->getElement('state')->setRequired();
}
if ($form->isValid()) {
//redirect to success page
} else {
//do nothing, display errors messages, refill form
}
}
or cleaner with extended Zend_Form_Element.
Here you can add custom validation like this in controller.
$state = "YOUR VALUE";
$form->state->setValue($state);
$form->getElement('state')->setRequired();
$form->getElement('state')->addValidator( 'Alpha', true, array( 'messages' => array( 'notAlpha' => "Please enter alphabetic character only in state name.
") ));
$mArr = array('state'=>$state);
if( !$form->isValid($mArr) ){
$myErrorArray[] = $form->getMessages();
$is_error = 1;
}
Here $myErrorArray have all error message that you apply on element state.

PHP and Javascript code needed to check if form fields are not empty

Javascript needed to prevent form submit if any of field is empty. all my form fields start names start with name=add[FieldName] those are the fields that need checking.
PHP, backend check before submiting to database double check to make sure all $POST are not empty
Here's a javascript function you can use. Just call it for each id belonging to the fields in question.
function isEmpty(field_id) {
var empty = false;
if (document.getElementById(field_id).value == null)
empty = true;
if (document.getElementById(field_id).value == "")
empty = true;
return empty;
}
If you have them predictably named, you could call this function in a loop. If, for instance, they were named field1, field2, ..., field23, then you could just have the following in your main code body:
for (i = 0; i < 24; i++) {
var emptyCheck = false;
if(isEmpty("field"+i)) {
emptyCheck = true;
//do whatever you want to do when a value is empty
}
}
I'm not going to write the javascript, but here's some PHP.
$valid = true;
foreach($_POST as $key)
{
if(!isset($key))
{
$valid = false;
}
}
if(!$valid)
{
header("Location: /path/to/form");
}

Zend_Form: Element should only be required if a checkbox is checked

I've got a Form where the user can check a checkbox "create new address" and can then fill out the fields for this new address in the same form.
Now I want to validate the fields of this new address ONLY if the checkbox has been checked. Otherwise, they should be ignored.
How can I do that using Zend_Form with Zend_Validate?
Thanks!
I think that the best, and more correct way to do this is creating a custom validator.
You can do this validator in two different ways, one is using the second parameter passed to the method isValid, $context, that is the current form being validated, or, inject the Checkbox element, that need to be checked for validation to occur, in the constructor. I prefer the last:
<?php
class RequiredIfCheckboxIsChecked extends Zend_Validate_Abstract {
const REQUIRED = 'required';
protected $element;
protected $_messageTemplates = array(
self::REQUIRED => 'Element required'
);
public function __construct( Zend_Form_Element_Checkbox $element )
{
$this->element = $element;
}
public function isValid( $value )
{
$this->_setValue( $value );
if( $this->element->isChecked() && $value === '' ) {
$this->_error( self::REQUIRED );
return false;
}
return true;
}
}
Usage:
class MyForm extends Zend_Form {
public function init()
{
//...
$checkElement = new Zend_Form_Element_Checkbox( 'checkbox' );
$checkElement->setRequired();
$dependentElement = new Zend_Form_Element_Text( 'text' );
$dependentElement->setAllowEmpty( false )
->addValidator( new RequiredIfCheckboxIsChecked( $checkElement ) );
//...
}
}
I have not tested the code, but I think it should work.
I didn't actually run this, but it should work within reason. I've done something similar before that worked, but couldn't remember where the code was.
<?php
class My_Form extends Zend_Form
{
public function init()
{
$checkbox = new Zend_Form_Element_Checkbox("checkbox");
$checkbox->setValue("checked");
$textField = new Zend_Form_Element_Text("text");
$this->addElements(array("checkbox", "text"));
$checkbox = $this->getElement("checkbox");
if ($checkbox->isChecked() )
{
//get textfield
$textField = $this->getElement("text");
//make fields required and add validations to it.
$textField->setRequired(true);
}
}
}
Here's what I do if I need to validate multiple elements against each other
$f = new Zend_Form();
if($_POST && $f->isValid($_POST)) {
if($f->checkbox->isChecked() && strlen($f->getValue('element')) === 0) {
$f->element->addError('Checkbox checked, but element empty');
$f->markAsError();
}
if(!$f->isErrors()) {
// process
...
...
}
}
I've been wondering how to do that in ZF as well, though never had to implement such form feature.
One idea that comes to mind is to create a custom validator that accepts the checkbox field as a parameter, and run it in a validator chain, as documented. If the checkbox is checked, validator could return failure. Then you can check whether all validations failed and only then treat form as having failed validation.
That level of customization of form validation could be inconvenient, so maybe using form's isValidPartial method would be better.
I created a custom validator that will make your element required based on the value of another zend form element.
Here's the full code. I hope this helps someone.
The idea is to create a custom validator and pass in the name of the conditional element and the value of that conditional element into the constructor. Zend_Validor's isValid method already has access to the value of the element you are attaching the validtor to along with all the form element names and values.
So, inside the isValid method you have all the information you need to determine if your form element should be a required element.
On Zend 1 extend the isValid method, where you set required depending on posted data for example:
public function isValid($data)
{
if (!empty($data['companyCar'])) {
$this->getElement('carValue')->setRequired(true);
}
return parent::isValid($data);
}
Thank you JCM for your good solution.
However 2 things I've noticed:
The isValid method of your validator has to return true in case of success.
The validator will not be executed during form validation without pass the allowEmpty option to false to the text field.

Categories