JSFiddle - React, Tailwind, and code Playground
HTML
<form action="mail" id="theform" name="theform" method="post">
<label>rut:</label>
<input name="rut" id="rut" type="text" placeholder="11111111-1" maxlength="12" max="12">
<label>email:</label>
<input name="email" id="email" type="text" placeholder="nombre@mail.cl">
<input class="submit" type="submit" name="submit" value="Enviar" />
</form>
CSS
body, input, textarea {
font-size:12px;
line-height:18px;
font-family:Verdana, Geneva, sans-serif;
}
input {width:200px;}
.submit {width:120px;}
#error {
color:red;
font-size:10px;
display:none;
}
.needsfilled {
background:red;
color:white;
}
JavaScript
$(document).ready(function() {
email = $("#email");
rut = $("#rut");
emptymail = "ingresa tu email.";
emptyrut = "ingresa tu rut.";
erroremail = "Email invalido.";
$("#theform").submit(function(){
if (rut.val().length < 1) {
rut.val(emptyrut);
rut.addClass("needsfilled");
return false;
}
if (email.val().length < 1) {
email.val(emptymail);
email.addClass("needsfilled");
return false;
}
else if (email.hasClass("needsfilled")) {
return false;
}
if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.val(erroremail);
email.addClass("needsfilled");
return false;
}
if ($(":input").hasClass("needsfilled")) {
return false;
}
});
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
//Funcion formato rut//
function formato_rut()
{
var sRut1 = document.getElementById("rut").value;
sRut1=sRut1.replace('-', '');// se elimina el guion
sRut1=sRut1.replace('.', '');// se elimina el primer punto
sRut1=sRut1.replace('.', '');// se elimina el segundo punto
sRut1 = sRut1.replace(/k$/,"K");
document.getElementById("rut").value=sRut1;
//contador de para saber cuando insertar el . o la -
var nPos = 0;
//Guarda el rut invertido con los puntos y el guión agregado
var sInvertido = "";
//Guarda el resultado final del rut como debe ser
var sRut = "";
for(var i = sRut1.length - 1; i >= 0; i-- )
{
sInvertido += sRut1.charAt(i);
if (i == sRut1.length - 1 )
sInvertido += "-";
else if (nPos == 3)
{
sInvertido += ".";
nPos = 0;
}
nPos++;
}
for(var j = sInvertido.length - 1; j >= 0; j-- )
{
if (sInvertido.charAt(sInvertido.length - 1) != ".")
sRut += sInvertido.charAt(j);
else if (j != sInvertido.length - 1 )
sRut += sInvertido.charAt(j);
}
//Pasamos al campo el valor formateado
document.getElementById("rut").value = sRut.toUpperCase();
}