我有一个类似的问题,我需要至少没有。文本字段和文本区域的字符数。此设置必须用于不同的表单和多个字段,因此我无法添加具有预定义表单 ID 和字段 ID 的过滤器。
我所做的是我创建了一个在编辑字段时可见的新设置,然后我验证了提交。您可以使用以下代码:
add_action( 'gform_field_standard_settings', 'minimum_field_setting', 10 );
add_action( 'gform_editor_js', 'editor_script' );
add_filter( 'gform_tooltips', 'add_encryption_tooltips' );
add_filter( 'gform_validation', 'general_validation' );
/**
* Adds the Minimum Characters Field to Form Fields
*
* @param integer $position
*/
function minimum_field_setting( $position ) {
//Position: Underneath Description TextArea
if ( $position == 75 ) {
?>
<li class="minlen_setting field_setting">
<label for="field_minlen" class="section_label">
<?php esc_html_e( 'Minimum Characters', 'gravityforms' ); ?>
<?php gform_tooltip( 'form_field_minlen' ) ?>
</label>
<input type="number"
id="field_minlen"
onblur="SetFieldProperty('minLength', this.value);"
value=""
/>
</li>
<?php
}
}
/**
* Adds Javascript to Gravity Forms in order to render the new setting field in their appropriate field types
*/
function editor_script() {
?>
<script type='text/javascript'>
//Append field setting only to text and textarea fields
jQuery.each(fieldSettings, function (index, value) {
if (index === 'textarea' || index === 'text') {
fieldSettings[index] += ", .minlen_setting";
}
});
//binding to the load field settings event to initialize the checkbox
jQuery(document).bind("gform_load_field_settings", function (event, field, form) {
if (field.type === 'textarea' || field.type === 'text') {
console.log(field);
if (typeof field.minLength !== "undefined") {
jQuery("#field_minlen").attr("value", field.minLength);
} else {
jQuery("#field_minlen").attr("value", '');
}
}
});
</script>
<?php
}
/**
* Add GF Tooltip for Minimum Length
*
* @param array $tooltips
*
* @return mixed
*/
function add_encryption_tooltips( $tooltips ) {
$tooltips['form_field_minlen'] = "<h6>Minimum Length</h6>Minimum number of characters for this field";
return $tooltips;
}
/**
* Validate Form Submission
*
* @param array $validation_result
*
* @return mixed
*/
function general_validation( $validation_result ) {
$form = $validation_result['form'];
foreach ( $form['fields'] as &$field ) {
if ( in_array( $field->type, [ 'text', 'textarea' ] ) && ! empty( $field->minLength ) ) {
$input_name = 'input_' . $field->id;
if ( isset( $_POST[ $input_name ] ) && $_POST[ $input_name ] != '' ) {
if ( strlen( $_POST[ $input_name ] ) < (int) $field->minLength ) {
$field->failed_validation = true;
$field->validation_message = 'Field must contain at least ' . $field->minLength . ' characters';
$validation_result['is_valid'] = false;
}
}
}
}
$validation_result['form'] = $form;
return $validation_result;
}
您可以将设置从最小长度更改为精确长度,然后相应地更新验证。