How do you get HTML5 inputs to validate if they are inside Polymer Web Components?

非 Y 不嫁゛ 提交于 2019-12-06 11:07:55

I'm not seeing the same problem you describe (using Chrome 36 and Polymer 0.3.3). The form validation works as expected with the following simple Polymer element (jsbin):

<polymer-element name="test-element" noscript>
  <template>
    <form>
      <label>Inside the element:</label>
      <input type="number" placeholder="Numbers only!">
      <input type="submit">
    </form>
  </template>
</polymer-element>

EDIT: In the examples you've shown, your host page's <form> is separated from the Polymer element's <input> due to the shadow DOM boundary. Is there a reason you're structuring things that way?

It doesn't look like any <input>s that exist in the shadow DOM actually get submitted along with a light DOM <form>, so the fact that they're not being validated is in a sense expected and the least of your concerns. (Take a look at the Network trace for this example and you'll see that only test=1234 gets submitted.)

Taking the approach in the example above and including the <form> in the Polymer element is enough to get the expected validation behavior that modern browsers offer. Alternatively, if all you really want is <template> and you don't need a full blown Polymer element, you could do something along the lines of (jsbin):

<form>
  <template is="auto-binding">
    <label>Inside the element:</label>
    <input type="number" placeholder="Numbers only!" value="{{myNumber}}">
  </template>
  <input type="submit">
</form>
<script>
  document.querySelector('template').myNumber = 34;
</script>

That works too, because once the <template> is bound, the contents are added directly to the page's DOM like any other element.

If you strongly that you can't refactor your code as described, then I think you'd need to address your concern via bugs against the web browsers in question and see if they have any willingness to start considering <input> elements in the shadow DOM as part of a light DOM's <form>.

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