问题
I am using Polymer Web Components and my application targets Chrome. On my form, outside the Web Components I have an input type='number', when I enter 'a' into the input and submit the form, I get a tooltip that says "Please enter a number."
However, I have another input type="number" that is in the Shadow DOM of a web component. When I enter 'a' into that field and submit the form, I get no tooltip. Is there anyway to make the behavior more consistent?
回答1:
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>.
来源:https://stackoverflow.com/questions/24615634/how-do-you-get-html5-inputs-to-validate-if-they-are-inside-polymer-web-component