<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
// Evento que se ejecuta cuando recibe el foco
$("input[type=text]").focus(function(){
// activamos la viñeta
$(this).next("span").css({display:"inline"});
// escondemos el error si estuviera activo
$(this).next("span").next().hide();
});
// Evento que se ejecuta cuando pierde el foco
$("input[type=text]").focusout(function(){
// escondemos la viñeta
$(".info").hide();
});
});
/**
* Función para validar que se haya introducido algun valor
*/
function validar(){
var nombre=$("form[name=miFormulario] input[name=nombre]");
var apellidos=$("form[name=miFormulario] input[name=apellidos]");
if(nombre.val().length==0)
{
// acivamos el error en el nombre
nombre.next("span").next().css({display:"inline"});
}
if(apellidos.val().length==0)
{
// activamos el error en el apellido
apellidos.next("span").next().css({display:"inline"});
}
if(nombre.val().length>0 && apellidos.val().length>0)
return true;
return false;
}
</script>
<style>
.mensaje {
top:-12px;
position:absolute;
margin-left:30px;
padding:7px 10px;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
background-color:#ccc;
border: 1px solid #808080;
}
.arrowLeft::after {
position:absolute;
left:-20px;
top:15px;
content:"\00a0";
display:block;
width:0px;
height:0px;
border-width:10px 20px 10px 10px;
border-style:solid;
border-color:transparent #ccc transparent transparent;
}
label {width:100px;display:inline-block;text-align:right;}
.miFormulario span {display:none}
.miFormulario p {position:relative;}
.error {color:#fff;background-color:red;}
.error:after {border-color:transparent red transparent transparent;}
.miFormulario input[type=submit] {padding:8px 10px;margin-left:110px;}
</style>
</head>
<body>
<form class="miFormulario" name="miFormulario" onSubmit="return validar();">
<p>
<label>Nombre</label>
<input type="text" name="nombre">
<span class="mensaje arrowLeft info">Introduce tu nombre</span>
<span class="mensaje arrowLeft error">El nombre es obligatorio</span>
</p>
<p>
<label>Apellidos</label>
<input type="text" name="apellidos">
<span class="mensaje arrowLeft info">Introduce tus apellidos</span>
<span class="mensaje arrowLeft error">Tus apellidos son obligatorios</span>
</p>
<p>
<input type="submit" value="Enviar">
</p>
</form>
</body>
</html>