带有错误句柄的自定义验证 Ninja 表单 [英] Custom validation Ninja form with error handle
问题描述
我在 WordPress 安装中使用 Ninja Form 插件.
I'm using Ninja Form plugin in my WordPress installation.
我的表单有 3 个输入文本字段.
My form has 3 input text fields.
在按下提交按钮后,我需要通过检查输入的值是否存在于我的数据库的自定义表中来验证此输入之一.
I need, after pressing the submit button, to validate one of this input by checking if the entered value exists in a custom table in my database.
如果该值不存在,则不应发生任何事情(Ninja Form 保存表单),如果存在,我需要添加 Ninja Form 错误并让用户更改输入以使用新值保存表单.
If the value doesn't already exists nothing should happen (Ninja Form save the form), if it exists I need to add a Ninja Form error and let the user change the input in order to save the form with a new value.
如何挂钩提交操作?我怎样才能在这个钩子中获得我需要的输入值?如果该值存在,如何添加 Ninja Form 错误以防止表单保存?
How can I hook the submit action? How can I get in this hook the input value I need? How can I add a Ninja Form error if the value exists in order to prevent the form save?
推荐答案
您可以使用 ninja_forms_submit_data
钩子执行此操作.在那里,您可以通过变量 $form_data
使用其 id 访问字段的值.将字段的错误消息添加到 $form_data['errors']
时,表单将不会被保存.
You can do this using the ninja_forms_submit_data
hook. There you can access the value of a field using its id through the variable $form_data
. When adding an error message for the field to $form_data['errors']
the form will not be saved.
像这样(在 functions.php
中):
add_filter('ninja_forms_submit_data', 'custom_ninja_forms_submit_data');
function custom_ninja_forms_submit_data($form_data)
{
$field_id = 2;
$field_value = $form_data['fields'][$field_id]['value'];
$exists = true; // Check your database if $field_value exists
if($exists)
{
$form_data['errors']['fields'][$field_id] = 'Value already exists';
}
return $form_data;
}
这篇关于带有错误句柄的自定义验证 Ninja 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!