getting errorMessage: controlling validationmessages through data-errormessage
by trixta
HTML
<script src="https://afarkas.github.io/webshim/js-webshim/minified/polyfiller.js"></script>
<form action="#">
<div class="form-row message-test">
<label for="email">email with data-errormessage</label>
<input data-errormessage='{"valueMissing": "Please enter your email adress.", "typeMismatch": "Your email is not correct."}' required="" type="email" id="email" />
<ul>
<li>$.getErrorMessage: <span class="getErrorMessage"></span>
</li>
<li>validationMessage: <span class="validationMessage"></span>
</li>
</ul>
</div>
<div class="form-row message-test">
<label for="email2">email without data-errormessage</label>
<input required="" type="email" id="email" />
<ul>
<li>$.getErrorMessage: <span class="getErrorMessage"></span>
</li>
<li>validationMessage: <span class="validationMessage"></span>
</li>
</ul>
</div>
<div class="form-row">
<input type="submit" />
</div>
</form>
<label class="lang-select">change lang
<select class="active-lang"></select>
</label>
CSS
form {
margin: 10px auto;
max-width: 600px;
min-width: 220px;
}
.form-row {
padding: 5px 10px;
}
label {
display: block;
margin: 3px 0;
}
.lang-select {
position: absolute;
top: 5px;
right: 5px;
}
.form-row input {
width: 220px;
padding: 3px 1px;
}
li {
margin: 3px 0 4px;
font-weight: bold;
}
li span {
display: block;
padding: 1px;
background: #eee;
font-weight: normal;
}
JavaScript
webshim.setOptions('forms', {
//show custom styleable validation bubble
replaceValidationUI: true,
customMessages: true
});
//start polyfilling
webshim.polyfill('forms');
//render messages
$(function () {
var renderMessages = function () {
$('.getErrorMessage', this).html($('input[type="email"]', this).getErrorMessage());
$('.validationMessage', this).html($('input[type="email"]', this).prop('validationMessage'));
};
//render/update on input and on start
$('.message-test').on('input', renderMessages).each(renderMessages);
//+ update on lang change
$(webshim.validityMessages).on('change', function () {
$('.message-test').each(renderMessages);
});
});
//end: render messages
//render activeLang-select
$(function () {
var langs = webshim.validityMessages.availableLangs.concat(['de', 'en', 'en-AU', 'en-GB', 'en-US']).sort();
langs.unshift('');
$('select.active-lang').each(function () {
var select = $(this);
var options = langs.map(function (lang) {
return '<option>' + lang + '</option>';
});
var onLangChange = function () {
select.val(this.__activeName || webshim.activeLang());
};
select.html(options)
.on('change', function () {
var value = select.val();
if (value) {
webshim.activeLang(value);
}
});
$(webshim.validityMessages)
.on('change', onLangChange)
.each(onLangChange);
});
});