The HTML5 spec defines some very interesting validation components, including pattern (for validating against a Regexp) and required (for marking a field as required). As best I can tell, however, no browser yet actually does any validation based on these attributes.
I found a comparison of HTML5 support across engines, but there is no information about validation there. In the browsers I've tried (Firefox 3.5.8 and Safari 4.0.4), no object has a checkValidity()
method, so I can't run the validations even though I can define them.
Is there any support for this feature out there so I can experiment?
Sure. Opera and Chromium. But you can test yourself:
function supportsValidity(){
var i = document.createElement('input');
return typeof i.validity === 'object'
}
Here's a link to a sandbox where you can see Opera and Chrome in action: http://jsfiddle.net/vaZDn/light/
I tested the following in Google Chrome:
<!DOCTYPE html>
<html>
<body>
<style>
.valid { color: #0d0; }
.invalid { color: #d00; }
</style>
<div id="output"></div>
<script>
function check(input) {
var out = document.getElementById('output');
if (input.validity) {
if (input.validity.valid === true) {
out.innerHTML = "<span class='valid'>" + input.id +
" is valid</span>";
} else {
out.innerHTML = "<span class='invalid'>" + input.id +
" is not valid</span>";
}
}
console.log(input.checkValidity());
};
</script>
<form id="testform" onsubmit="return false;">
<label>Required:
<input oninput="check(this)" id="required_input"
required />
</label><br>
<label>Pattern ([0-9][A-Z]{3}):
<input oninput="check(this)" id="pattern_input"
pattern="[0-9][A-Z]{3}"/>
</label><br>
<label>Min (4):
<input oninput="check(this)" id="min_input"
type=number min=4 />
</label><br>
</form>
</body>
</html>
Stangely, the <element>.validity.valid
property seems to work correctly, but calling <element>.checkValidity()
always returns true, so it looks like that's not implemented yet.
checkValidity() is suppost to work on either the form as a whole or an individual input.
taken from a List Apart - http://www.alistapart.com/articles/forward-thinking-form-validation/
"valid = element . checkValidity() Returns true if the element's value has no validity problems; false otherwise. Fires an invalid event at the element in the latter case." http://www.w3.org/TR/2011/WD-html5-20110525/forms.html#client-side-form-validation
W3C - working draft.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With