我正在使用Wordpress 5.1.1上的忍者表单提交一个简单的表单。但是,我需要一个简单的服务器端验证。我已经在文档和网络上筛选了几天,但是我找不到解决这个问题的方法。
到目前为止,我已经能够将我的函数附加到忍者表单的ninja_forms_submit_data
网络钩子上。我已经确认PHP确实正在执行。然而,当我提交表单时,当我试图返回一个自定义错误时,它被“处理”卡住了。我相信这与AJAX响应格式有关,但我不能确定。甚至可能是网站安全阻止了请求,但我对此表示怀疑。在我看来,更有可能的是,我从根本上缺乏对NinjaForms在后端的操作方式的误解。
在这一点上,我甚至愿意做客户端验证(上下文中的安全性并不重要)。但我甚至不确定如何实现这一目标。
我的背景主要是C/C++、Java、Python和Ruby。PHP让我有点不知所措。如果您能提供任何帮助,我们将不胜感激。
这是在我的过滤器中调用的验证检查。无论我是否将$errors
设置为[]
,提交都将在处理过程中冻结。只有在执行if( !validateSite( $form_data, $field_id ) )
块时才会发生这种情况。否则,表单提交得非常好。只有在没有要报告的错误时,处理才会冻结。
function validateSite($form_data, $field_id){
// $site_code = $form_data['fields'][$field_id]['value'];
$form_fields = $form_data[ 'fields' ];
foreach( $form_fields as $field )
{
$field_id = $field[ 'id' ];
$field_key = $field[ 'key' ];
$field_value = $field[ 'value' ];
// Example Field Key comparison
if( "site_code_1552245398425" == $field_key )
//I Strongly Suspect that this site code is never found,
//as I can never get this method to return false without
//hard-setting the default return. (Regardless whether or
//not the input is even or odd.)
{
if(intval($field_value) % 2 != 0) //EXAMPLE TEST
{
return true;
}
else
{
return false;
}
}
}
return false; //hard set to false
}
这是执行的筛选器:
add_filter( 'ninja_forms_submit_data', function( $form_data ){
$field_id = 'nf-field-21';
if( !validateSite( $form_data, $field_id ) )
{
$errors = [];
$form_fields = $form_data[ 'fields' ];
foreach( $form_fields as $field ) //iterate through the fields
{
$field_id = $field[ 'id' ];
$field_key = $field[ 'key' ];
$field_value = $field[ 'value' ];
if($field_key == "site_code_1552245398425")
{
//$errors = ['fields'][$field_id] = "INVALID SITE CODE";
$errors = ['fields' => [$field_id => "INVALID SITE CODE"]];
}
}
/*
$errors = [ 'fields' => [ 'nf-field-21' => __( 'Invalid Site Code.', 'my-plugin' ) ],];
*/
$response = [
'errors' => $errors,
];
echo wp_json_encode( $response );
wp_die(); // this is required to terminate immediately and return a proper response
}
// If no errors, be sure to return the $form_data.
return $form_data;
});
发布于 2019-04-01 02:19:18
在搜索了一段时间后,我设法找到了我自己的答案。考虑到缺乏关于这个主题的详细文档,我相信有人可能会发现这一点很有帮助。下面的代码可以有效地工作。THIS链接帮了很大的忙。
function validateSite($form_data, $fieldID)
{
if(intval($form_data['fields'][$fieldID]['value']) % 31 == 0)
{
return true; //No errors
}
else
{
return false; //ERROR!
}
}
add_filter( 'ninja_forms_submit_data', function( $form_data ){
$field_id = 21; //Field ID is NUMERICAL and not a string like 'nf-field-21', despite what you see in the front-end html.
if( !validateSite( $form_data, $field_id ) )
{
//This is the EASY way to set an error on a field.
$form_data['errors']['fields'][21] = "INVALID SITE CODE";
}
// If no errors, be sure to return the $form_data.
return $form_data;
});
https://stackoverflow.com/questions/55443553
复制相似问题