JavaScript preprocessors can help make authoring JavaScript easier and more convenient. For instance, CoffeeScript can help prevent easy-to-make mistakes and offer a cleaner syntax and Babel can bring ECMAScript 6 features to browsers that only support ECMAScript 5.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
HTML Settings
Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.
<form id="form">
<label for="nome">Nome</label>
<input required id="nome" name="nome">
<label for="idade">Idade</label>
<input type="number" name="idade">
<label for="senha">Senha</label>
<input required type="password" id="senha" name="senha" aria-describedby="criterios-senha">
<p id="criterios-senha">A senha deve ter letras e números e ter pelo menos 8 caracteres.</p>
<button>Enviar</button>
</form>
label, button {
display: block;
margin-top: 0.75em;
}
input, .erro-validacao__mensagem {
display: inline-block;
font: inherit;
padding: 0.25em 0.5em;
}
.erro-validacao__mensagem {
background-color: #FCC;
border: 1px solid #F00;
color: #500;
margin: 0 0 0 1em;
}
.erro-validacao__mensagem::before {
/* Ícone retirado de https://commons.wikimedia.org/wiki/File:Feedbin-Icon-error.svg */
background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48c3ZnIHZlcnNpb249IjEuMiIgYmFzZVByb2ZpbGU9InRpbnkiIGlkPSJMYXllcl8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjIwcHgiIGhlaWdodD0iMTZweCIgdmlld0JveD0iMCAwIDIwIDE2IiB4bWw6c3BhY2U9InByZXNlcnZlIj48cGF0aCBmaWxsPSIjRDYxRjMzIiBkPSJNMTAsMEwwLDE2aDIwTDEwLDB6IE0xMSwxMy45MDhIOXYtMmgyVjEzLjkwOHogTTksMTAuOTA4di02aDJ2Nkg5eiIvPjwvc3ZnPg==);
content: '';
display: inline-block;
height: 16px;
width: 20px;
margin-right: 1em;
}
.erro-validacao__campo {
border: 1px solid #F00;
}
const PREFIXO_BACKUP = 'data-old-';
function adicionaComBackup(elemento, atributo, novoValor) {
if (elemento.hasAttribute(atributo)) {
const valorAtual = elemento.getAttribute(atributo);
elemento.setAttribute(PREFIXO_BACKUP + atributo, valorAtual);
elemento.setAttribute(atributo, novoValor + ' ' + valorAtual);
} else {
elemento.setAttribute(atributo, novoValor);
}
}
function restauraBackup(elemento, atributo) {
const atributoBackup = PREFIXO_BACKUP + atributo;
if (elemento.hasAttribute(atributoBackup)) {
const valorBackup = elemento.getAttribute(atributoBackup);
elemento.setAttribute(atributo, valorBackup);
elemento.removeAttribute(atributoBackup);
} else {
elemento.removeAttribute(atributo);
}
}
function adicionaErro(campo, mensagem) {
const elemento = document.createElement('p'),
paiCampo = campo.parentNode,
idGerado = 'erro' + new Date().getTime();
elemento.id = idGerado;
elemento.innerHTML = mensagem;
elemento.className = 'erro-validacao__mensagem';
// insere a mensagem logo após o campo
paiCampo.insertBefore(elemento, campo.nextSibling);
// marca o campo com cor diferente
campo.classList.add('erro-validacao__campo');
adicionaComBackup(campo, 'aria-describedby', idGerado);
}
function apagaErrosAntigos(form) {
const mensagensAntigas = form.querySelectorAll('.erro-validacao__mensagem');
for (var i = 0, total = mensagensAntigas.length; i < total; i++) {
mensagensAntigas[i].parentNode.removeChild(mensagensAntigas[i]);
}
// apaga marcação diferente nos campos com erro
const camposComErro = form.querySelectorAll('.erro-validacao__campo');
for (var i = 0, total = camposComErro.length; i < total; i++) {
camposComErro[i].classList.remove('erro-validacao__campo');
restauraBackup(camposComErro[i], 'aria-describedby');
}
}
function senhaValida(senha) {
return senha.length >= 8 && /\d/.test(senha) && /\w/.test(senha);
}
function valida(campo) {
if (campo.required && campo.value.trim() === '') {
adicionaErro(campo, 'Este campo é obrigatório.');
return false;
}
// validação simplificada apenas para o exemplo
if (campo.type === 'number' && !/^\d*$/.test(campo.value)) {
adicionaErro(campo, 'Preencha apenas com números válidos!');
return false;
}
// validação customizada para senha
if (campo.id === 'senha' && !senhaValida(campo.value)) {
adicionaErro(campo, 'Senha inválida!');
return false;
}
return true;
}
form.setAttribute('novalidate', '');
form.addEventListener('submit', function(e) {
let valido = true;
e.preventDefault();
apagaErrosAntigos(form);
for (let i = 0; i < form.length; i++) {
if (!valida(form[i])) {
if (valido) {
// primeiro campo com erro; ganha foco
form[i].focus();
}
valido = false;
}
}
if (valido) {
form.submit();
}
});
Also see: Tab Triggers