JavaFX WebView: how to check if form is valid?

若如初见. 提交于 2020-05-16 21:50:49

问题


Is there a way to tell if a form is valid from Java?

Basically, a method that returns true if all input fields constrains are satisfied and false otherwise.

Strangely enough, org.w3c.dom.html.HTMLFormElement doesn't actually have a checkValidity() method.

EDIT:

Even more strangely, the implementation com.sun.webkit.dom.HTMLFormElementImpl does support the method checkValidity(). Unfortunately, the package com.sun.webkit is not accessible directly and thus the method is unavailable.


回答1:


DOM objects like HTMLFormElement only model structure. They are not capable of executing JavaScript.

However, WebEngine itself does have a JavaScript interpreter, which you can invoke using the executeScript method:

boolean valid = (Boolean) webView.getEngine().executeScript(
    "document.forms[0].checkValidity();");

The checkValidity() method is documented here and here.




回答2:


Cast the form to JSObject

Most HTML Java elements, including HTMLFormElement, can be directly cast to the JavaScript object JSObject. It is then trivial to validate the form.

Example:

JSObject jsObject = (JSObject) form;
boolean valid = (boolean) jsObject.call("checkValidity");


来源:https://stackoverflow.com/questions/59274247/javafx-webview-how-to-check-if-form-is-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!