Validate a input text filed on Gravity Form? - validation

How to validate a input text filed only allow letters not allow Number and symbol on Gravity Form?
add_filter( 'gform_field_validation_13_6', function( $result, $value, $form, $field ) {
if (preg_match('#^[A-Za-z\s]{1,}$#', $a) == 1) {
echo "ok\n";
$result['is_valid'] = false;
$result['message'] = 'Please enter only letters';
}
return $result;
}, 10, 4 );

Related

Display an admin notice after a term creation in WordPress

I do not understand how to display a notice after a term creation in WordPress.
I have a custom field in a custom taxonomy. On the save event, I check if the value is incorrect and in this case, I want to display a notice.
I have a similar situation in the post editor but here I have solved with add_settings_error and admin_notices.
This method does not work in the term creation screen because in this scenario, there is an AJAX request and the page does not reload.
Here is the code about term screen:
add_action('create_account', 'save_start_amount_data__fr');
add_action('admin_notices', 'display_start_amount_data_validation_error__fr');
function save_start_amount_data__fr($term_id) {
if (
!isset($_POST['start_amount_nonce']) ||
!wp_verify_nonce($_POST['start_amount_nonce'], 'start_amount_nonce')
) {return $term_id;}
if (
(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
) {return $term_id;}
if (
!isset($_POST['taxonomy']) ||
$_POST['taxonomy'] != 'account' ||
!current_user_can('edit_posts')
) {return $term_id;}
if (
!isset($_POST['start_amount'])
) {return $term_id;}
if (
!preg_match('/^[-]?[0-9]+([,]?[0-9]{1,2})?$/', $_POST['start_amount'])
) {validate_start_amount_data__fr();}
$start_amount = $_POST['start_amount'];
$start_amount = sanitize_text_field($start_amount);
update_term_meta($term_id, 'start_amount', $start_amount);
return $term_id;
}
function validate_start_amount_data__fr() {
add_settings_error(
'incorrect_start_amount_value',
'incorrect_start_amount_value',
__('Please review the start amount value because it is in an incorrect format.', 'fr'),
'error'
);
set_transient('settings_errors', get_settings_errors(), 30);
return null;
}
function display_start_amount_data_validation_error__fr() {
$errors = get_transient('settings_errors');
if (!$errors) {return null;}
$message = '<div class="notice notice-error"><ul>';
foreach($errors as $error) {
$message .= '<li>' . $error['message'] . '</li>';
}
$message .= '</ul></div>';
echo $message;
delete_transient('settings_errors');
remove_action('admin_notices', 'display_start_amount_data_validation_error__fr');
return null;
}
I hope that someone can help me to achieve my goal.
See below the method that I'm using on a Custom Posts to display notifications.
Take a look to the filter "redirect_post_location".
//Actions
$this->loader->add_action( 'admin_notices', $plugin_admin, 'general_admin_notice' );
$this->loader->add_action( 'save_post', $plugin_admin, 'admin_save_post' );
/**
* Admin Save the Meta box values
*
* #since 1.0.0
*/
function admin_save_post( $id ) {
/* --- security verification --- */
if(!wp_verify_nonce($_POST['attachment_nonce'], plugin_basename(__FILE__))) {
return $id;
} // end if
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $id;
} // end if
if('page' == $_POST['post_type']) {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} else {
if(!current_user_can('edit_page', $id)) {
return $id;
} // end if
} // end if
/* - end security verification - */
// Make sure the file array isn't empty
if(!empty($_FILES['secure_doc_attachment']['name'])) {
$upload = $this->admin_upload_file( $_FILES , $id );
if (!$upload){
add_filter('redirect_post_location', function($loc) {
return add_query_arg( 'error', 1, $loc );
});
return $post_id;
}
}
}
/**
* Admin Notice
*
* #since 1.0.0
*/
function general_admin_notice(){
global $pagenow;
if ( 'post.php' === $pagenow && isset($_GET['post']) && 'custom-post' === get_post_type( $_GET['post'] ) ){
if ( isset($_GET['error'])) {
echo '<div class="notice notice-error is-dismissible">
<p>Error uploading the attachment.</p>
</div>';
}
}
}
See other useful link here:
https://wordpress.stackexchange.com/questions/124132/admin-post-update-redirection-to-posts-screen
Regards.
Ed.

How to compare value from table in call back function in codeigniter form validaiton

This is my Callback function for form validation in CodeIgniter
public function user_check($str)
{
if ($str == 'sounitkar13')
{
return TRUE;
}
else
{
$this->form_validation->set_message('user_check', 'The %s is not found in our record');
return FALSE;
}
}
right now i am comparing $str with "sounitkar13" but i have a table with 100 username stored so i want to compare with those 100 user names and if it matches with any of those 100 then return TRUE otherwise FALSE. ( it is reverse of is_unique function.
you have to do condition on table rows using where condition
$query = $this->db->get_where('table', array(
'username' => $str
));
$count = $query->num_rows();
if ($Count != 0)
{
return TRUE;
}
else
{
$this->form_validation->set_message('user_check', 'The %s is not found in our record');
return FALSE;
}

Regnerate all files in the preview with Dropzone after an error occured

I am trying to use dropzone.js combined with other form elements and everything is working fine except one thing. I have some validation rules for other form elements and when one of the validation rules fails, it sends errors with ajax response. When an error occurs all dropzone files gets cancelled from the queue. Then I need to add dropped files manually again and submit the form. Is there any way to keep all image files in the queue even if an error occurs so that I can try re-sending them again ?
here is my dropzone configuration :
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
addRemoveLinks:true,
This is the method which is called after form submit:
public function save($request)
{
$request = $request->all();
// Create a new validator instance from our validation rules
$validator = Validator::make($request, $this->validationRules);
// If validation fails, we'll exit the operation now.
if ($validator->fails())
{
// Ooops.. something went wrong
$this->errors = $validator->errors();
return false;
}
$user_id = getLoggedInId();
$request['operator_id'] = $this->operator->getId($user_id);
$result = $this->visit->add($request);
if ($result == 'updated')
{
$this->success = 'Successfully Updated!';
return $result;
}
elseif ($result == 'failed')
{
$this->errors = 'failed!';
return false;
}
elseif ($result == 'notAllowed')
{
$this->errors = 'Not Allowed to update this record';
return false;
}
else
{
if (Input::file('file'))
{
$visit_id = $result->id;
$files = Input::file('file');
$today = Carbon::now();
$patient_id = Input::get('patient_uid'); //need more validation later on
$center_id = substr($patient_id, 0, 3);
$uid = substr($patient_id, -5);
$upload_dir = $center_id . '/' . $today->year . '/' . $today->month . '/';
foreach ($files as $file)
{
// public/uploads
$response = $this->report->upload($file, $upload_dir, $visit_id, $uid);
if ($response['error'])
{
$this->errors = $response['message'];
return false;
}
}
}
$this->success = trans('patients/visit_form.successfully_created');
return $result;
}
and this is the logic for submitting form:
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length > 0)
{
myDropzone.processQueue();
} else {
submitVisitForm();
}
});

Joomla - Custom error message from form invalid fields

I am developing Custom Component for Joomla.
I did well in validating field by adding custom rule. But if entered value does not pass through my validation, it gives error as "Invalid Field: My Field Name"
I want to replace this with my own message.
I know I can use "JText::_('LANGUAGE_STRING'). But I'm not sure where do I need to add it.
I have custom rule called "validemails" which returns false in client side as well as server side validation.
My Client side Validation is: (components/com_helpdesk/models/forms/create.js)
jQuery(document).ready(function () {
document.formvalidator.setHandler('validemail', function (value) {
var emails = [value];
if (value.indexOf(';') !== -1) {
emails = value.split(';');
}
else if(value.indexOf(',') !== -1) {
emails = value.split(',');
}
regex = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var result = false;
emails.each(function (value) {
result = regex.test(jQuery.trim(value));
if (result === false) {
return false;
}
});
return result;
});
});
My Server Side Validation is: (components/com_helpdesk/models/rules/validemail.php)
use Joomla\Registry\Registry;
JFormHelper::loadRuleClass('email');
class JFormRuleValidemail extends JFormRuleEmail {
public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null) {
$emails = array($value);
if (strpos($value, ';') !== false) {
$emails = explode(';', $value);
}
else if (strpos($value, ',') !== false) {
$emails = explode(',', $value);
}
foreach ($emails as $email) {
if (!parent::test($element, trim($email))) {
return false;
continue;
}
}
return true;
}
}
Please note that I'm developing Front-end view of Component not back-end.
Well fortunately, I got my server side validation working by this way:
use Joomla\Registry\Registry;
JFormHelper::loadRuleClass('email');
class JFormRuleValidemail extends JFormRuleEmail {
public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null) {
$emails = array($value);
if (strpos($value, ';') !== false) {
$emails = explode(';', $value);
}
else if (strpos($value, ',') !== false) {
$emails = explode(',', $value);
}
foreach ($emails as $email) {
if (!parent::test($element, trim($email))) {
***$element->addAttribute('message', JText::_('COM_HELPDESK_ERROR_EMAIL').' '.$value);***
return false;
continue;
}
}
return true;
}
}
I got the solution. May be it will be useful for other googlers. Below is a code snippet for client side validation. Put below code in your custom JS:
jQuery('.validate').click(function (e) {
var fields, invalid = [], valid = true, label, error, i, l;
fields = jQuery('form.form-validate').find('input, textarea, select');
if (!document.formvalidator.isValid(jQuery('form'))) {
for (i = 0, l = fields.length; i < l; i++) {
if (document.formvalidator.validate(fields[i]) === false) {
valid = false;
invalid.push(fields[i]);
}
}
// Run custom form validators if present
jQuery.each(document.formvalidator.custom, function (key, validator) {
if (validator.exec() !== true) {
valid = false;
}
});
if (!valid && invalid.length > 0) {
error = {"error": []};
for (i = invalid.length - 1; i >= 0; i--) {
label = jQuery.trim(jQuery(invalid[i]).data("label").text().replace("*", "").toString());
if (label) {
if(label === 'Subject') {
error.error.push('Please Enter Subject');
}
if(label === 'Description') {
error.error.push('Please Enter Description');
}
if(label === 'Priority') {
error.error.push('Please Select Priority');
}
if(label === 'Email CCs') {
error.error.push('Please Enter proper Emails in CC section');
}
if(label === 'Email BCCs') {
error.error.push('Please Enter proper Emails in BCC section');
}
}
}
}
Joomla.renderMessages(error);
}
e.preventDefault();
});

Why does this webform uploaded file via ajax throw an error in Drupal 7?

I have a webform and mymodule which alters it. The webform has a field stelle which gets populated based on the url query. For instance, if ?stelle=10 the field gets populated by the title of node with nid 10. If the query ?stelle is non-existant or followed by a nid which does not exist (is not of a certain content type) or does not contain a certain string the form will be redirecting to mynode?stelle=initiativ. The form has 2 fields to upload files via ajax, works good so far. Here is my code:
<?php
/**
* Altering the form! this will add class to the file upload/ remove buttons
*/
function mymodule_form_alter(&$form, &$form_state, $form_id) {
$conf = mymodule_defaults();
if ($form_id == 'webform_client_form_' . $conf['nid']) {
if (isset($form['submitted']['field1'])) {
$form['submitted']['field1']['#process'] = array('mymodule_my_file_element_process');
}
if (isset($form['submitted']['field2'])) {
$form['submitted']['field2']['#process'] = array('mymodule_my_file_element_process');
}
$nid = $form['#node']->nid;
$form['actions']['submit']['#ajax'] = array(
'callback' => 'mymodule_webform_js_submit',
'wrapper' => 'webform-client-form-' . $nid,
'method' => 'replace',
'effect' => 'fade',
);
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
$hide_components = array(
'einleitung_standard',
'einleitung_initiativ',
);
$unhide_components = array();
if ($form['submitted']['stelle']['#default_value'] == '') {
$redirect_form = true;
}
elseif (is_numeric($form['submitted']['stelle']['#default_value'])) {
$nid = $form['submitted']['stelle']['#default_value'];
$node = node_load($nid);
if ($node === false || (isset($node->type) && $node->type !== 'job')) {
$redirect_form = true;
}
else {
$type = $node->type;
if ($type == 'job') {
$form['submitted']['stelle']['#default_value'] = $node->title;
$form['submitted']['stelle']['#attributes']['disabled'] = 'disabled';
$form['submitted']['related']['#value'] = $nid;
$unhide_components = array(
'einleitung_standard'
);
}
}
}
elseif ($form['submitted']['stelle']['#default_value'] == 'initiativ') {
// unset($form['submitted']['stelle']);
$form['submitted']['related']['#value'] = 'initiativ';
$unhide_components = array(
'einleitung_initiativ'
);
}
}
else {
// $redirect_form = true;
// this causes an error
}
This is the weird part:
$redirect_form = false;
$maintenance = false;
if (isset($form['submitted']['stelle']['#default_value']) && $form['submitted']['stelle']['#default_value'] !== '') {
...
else {
// $redirect_form = true;
// this causes an error
}
When I active the line to redirect the form when the if condition is false, the button to upload a file via ajax throws an error alert on click (see bottom for error). To me, this looks like the form alter hook is being called again when the file upload button is clicked without having my field stelle available - is that right? How to fix this?
And now the rest of the module, basically just alterings:
else {
// $redirect_form = true;
// this causes an error
}
foreach ($unhide_components as $key => $component) {
if (is_array($component)) {
foreach ($component as $_key => $_component) {
$index = array_search($_component, $hide_components[$key]);
if ($index !== false) {
unset($hide_components[$key][$index]);
}
}
}
else {
$index = array_search($component, $hide_components);
if ($index !== false) {
unset($hide_components[$index]);
}
}
}
// hide
foreach ($hide_components as $k=>$hc1){
if (is_array($hc1)) {
foreach ($hc1 as $hc2) unset($form['submitted'][$k][$hc2]);
} else {
unset($form['submitted'][$hc1]);
}
}
if ($redirect_form) drupal_goto('node/'.$conf['nid'], array('query'=>array('stelle'=>'initiativ')), 301);
}
}
function mymodule_my_file_element_process($element, &$form_state, $form) {
$element = file_managed_file_process($element, $form_state, $form);
$element['upload_button']['#attributes'] = array('class' => array('button'));
$prefix = '<label class="browse-slave">';
$prefix .= '<span class="button">' . t('Choose a file') . '</span>';
$element['upload']['#prefix'] = $prefix;
$element['upload_button']['#prefix'] = '</label>';
$element['remove_button']['#attributes'] = array('class' => array('button'));
$element['remove_button']['#prefix'] = '</label>';
return $element;
}
function mymodule_webform_js_submit($form, $form_state) {
// define the $sid variable (submission id from webform)
$sid = $form_state['values']['details']['sid'];
// if we have a sid then we know the form was properly submitted, otherwise, we'll just return the existing $form array
if ($sid) {
// first we have to load up the webform node object
$node = node_load($form_state['values']['details']['nid']);
// create an array up with the confirmation message, retreived from the webform node
$confirmation = array(
'#type' => 'markup',
'#markup' => check_markup($node->webform['confirmation'], $node->webform['confirmation_format'], '', TRUE),
);
// return the confirmation message
return $confirmation;
}
else {
// return the form
return $form;
}
}
The AJAX error is something like described here. Changing server/php settings didnt help it.
Thanks!
The form builder (and any hook alters) will be run when a form is validated, which happens on #ajax actions.
I like to throw static custom data in $form['#someProperty'] so that it's available in the build, validate, and submit functions. Something like this should help you:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
// ...
if (isset($_GET['stelle'])) {
$form['#stelle'] = $_GET['stelle']; // This will always be there.
}
// ...
}
Another option would be to throw the $node that you load in the form, like $form['#stelle_node'] = node_load(...) and obviously only do that when the nid is actually available to you, so that you don't overwrite it with empty data when the form builder runs again in the future.
When i was working with ajax in drupal 6 the hash symbol in url or request caused an error everytime..... so i replaced url with this
data.url.replace(/%2523/, '%23');

Resources