jQuery-validate Example
by paraselixir
HTML
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
<textarea class='message'></textarea>
<label for="name">Bits left <span class="left">1120</span></label>
<!––
男装 - triple bytes char example
-->
</form>
CSS
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
.numbers {
display: block;
width: 100px;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
JavaScript
$(document).ready(function() {
var maxSize =1120,sizeLeft,msgstring,msgstringSize;
$('.message').on('keyup', function() {
$(".left").html(maxSize);
msgstring = $(this).val();
msgstringSize = parseInt(getByteLength(msgstring));
sizeLeft = maxSize - msgstringSize
$(".left").html(sizeLeft);
});
function getByteLength(normal_val) {
// Force string type
normal_val = String(normal_val);
var byteLen = 0;
for (var i = 0; i < normal_val.length; i++) {
var c = normal_val.charCodeAt(i);
byteLen += c < (1 << 7) ? 1 :
c < (1 << 11) ? 2 :
c < (1 << 16) ? 3 :
c < (1 << 21) ? 4 :
c < (1 << 26) ? 5 :
c < (1 << 31) ? 6 : Number.NaN;
}
return byteLen*8;
}
});