1

在 Tapestry 5 中,我需要在表单中记录(通过谷歌分析)每个单独的表单字段何时完成并成功通过客户端验证。

我需要实时为每个单独的字段执行此操作,即使未提交表单,所以等到表单提交并在服务器上执行此操作不是一种选择。

有没有办法(开箱即用)挂钩 Tapestry 5 提供的 javascript 客户端验证的成功/失败?

我能想到的两种可能性是:

  1. Tapestry api 为成功/失败事件提供回调函数。
  2. 在成功/失败时监听一些 Tapestry 自定义事件。

但是我在文档中找不到关于这些现有的任何一个的任何内容。这些选项中的任何一个都是可能的,还是有其他方法可以实现?

4

2 回答 2

2

您可能能够附加客户端事件侦听器来实现您想要的。看看Tapestry.FormEventManager.handleSubmitTapestry.js。表单提交会触发以下客户端事件:

/**
 * Event that allows observers to perform cross-form validation after
 * individual fields have performed their validation. The form element is
 * passed as the event memo. Observers may set the validationError property
 * of the Form's Tapestry object to true (which will prevent form
 * submission).
 */
FORM_VALIDATE_EVENT: "tapestry:formvalidate",

/**
 * Event fired just before the form submits, to allow observers to make
 * final preparations for the submission, such as updating hidden form
 * fields. The form element is passed as the event memo.
 */
FORM_PREPARE_FOR_SUBMIT_EVENT: "tapestry:formprepareforsubmit",

/**
 * Form event fired after prepare.
 */
FORM_PROCESS_SUBMIT_EVENT: "tapestry:formprocesssubmit",

/**
 * Event, fired on a field element, to cause observers to validate the
 * input. Passes a memo object with two keys: "value" (the raw input value)
 * and "translated" (the parsed value, usually meaning a number parsed from
 * a string). Observers may invoke Element.showValidationMessage() to
 * identify that the field is in error (and decorate the field and show a
 * popup error message).
 */
FIELD_VALIDATE_EVENT: "tapestry:fieldvalidate",

/**
 * Event notification, on a form object, that is used to trigger validation
 * on all fields within the form (observed by each field's
 * Tapestry.FieldEventManager).
 */
FORM_VALIDATE_FIELDS_EVENT: "tapestry:validatefields",
于 2013-07-12T07:43:21.897 回答
1

一位同事建议Tapestry.FieldEventManager.validateInput使用 ProptypeJS Class.create 覆盖该函数。

Tapestry.FieldEventManager = Class.create(Tapestry.FieldEventManager, {
                                 validateInput : function($super) {
                                     var isValidationFailure = $super();

                                     // can use this.field inside this function to access the field being validated

                                     if(!isValidationFailure) {
                                         // LOGIC ON VALIDATION SUCCESS
                                     } else {
                                         // LOGIC ON VALIDATION FAILURE
                                     }
                                     return isValidationFailure;
                                 }
                             });

这很好地解决了这个问题,允许清晰可读的代码和轻松访问超级实现和实际字段本身,我需要执行我的跟踪逻辑。最好的部分是它可以正常工作,当它失去焦点时会在每个单独的表单字段上调用 ​​validateInput。不需要驱动验证引擎的事件的详细知识或混乱的代码!

仅供参考 validateInput 还将在表单提交时为每个表单字段运行 - 可以通过覆盖 Tapestry.FormEventManager.handleSubmit 以挂钩表单提交逻辑来解决......但这有点超出了这个答案的范围。

于 2013-07-19T22:25:22.773 回答