前言
Bricks 1.4 引入了 bricks/inputs/valid 钩子,允许你在 Bricks 提交表单之前验证用户输入。
用法
将代码加入子主题的 functions.php:
add_filter( 'bricks/form/validate', function( $errors, $form ) {
$form_id = $form->get_element_id();
$fields = $form->get_fields();
// Example: Only validate a specific form
if ( $form_id === 'my_form_id' ) {
// Check if email domain is allowed
$email_field_id = 'form-field-email';
if ( isset( $fields[ $email_field_id ] ) ) {
$email = $fields[ $email_field_id ];
if ( strpos( $email, '@example.com' ) === false ) {
$errors[] = esc_html__( 'Please use an @example.com email address.', 'my-domain' );
}
}
}
return $errors;
}, 10, 2 );
参数
$errors(array):验证错误消息数组。$form(object):Form 集成实例。
示例代码
筛选返回值
add_filter( 'bricks/form/validate', function( $errors, $form ) {
$form_id = $form->get_element_id();
$fields = $form->get_fields();
// Example: Only validate a specific form
if ( $form_id === 'my_form_id' ) {
// Check if email domain is allowed
$email_field_id = 'form-field-email';
if ( isset( $fields[ $email_field_id ] ) ) {
$email = $fields[ $email_field_id ];
if ( strpos( $email, '@example.com' ) === false ) {
$errors[] = esc_html__( 'Please use an @example.com email address.', 'my-domain' );
}
}
}
return $errors;
}, 10, 2 );
根据条件短路返回原值
根据条件跳过或修改返回值:
add_filter( 'bricks/form/validate', function( $value, $errors ) {
if ( is_admin() ) { return $value; }
// TODO: custom logic here
return $value;
} );
补充说明
更多细节可参考 官方文档。