Estava procurando um javascript para validar decimais, achei várias funções mas do jeito que queria não achei. Então criei essa função javascript para validar um decimal com 2 casas decimais.
function FormatDecimal(e) {
var keyCode = window.event.keyCode;
if (e.value.search(',') > 1 && keyCode != 44) {
var index = e.value.indexOf(',')
if (index + 1 + 2 <= e.value.length) {
window.event.keyCode = 0;
}
else if (keyCode == 44) {
if (e.value.search(',') >= 1) {
window.event.keyCode = 0;
}
}
else if ((window.event.keyCode <= 45 || window.event.keyCode == 47) ||
window.event.keyCode >= 58 || window.event.keyCode == 32 || window.event.keyCode == 46) {
window.event.keyCode = 0;
}
}
else
{
if (keyCode == 44) {
if (e.value.search(',') >= 1) {
window.event.keyCode = 0;
}
}
else if ((window.event.keyCode <= 45 || window.event.keyCode == 47) ||
window.event.keyCode >= 58 || window.event.keyCode == 32 || window.event.keyCode == 46) {
window.event.keyCode = 0;
}
}
}
if (e.value.search(',') > 1 && keyCode != 44) {
var index = e.value.indexOf(',')
if (index + 1 + 2 <= e.value.length) {
window.event.keyCode = 0;
}
else if (keyCode == 44) {
if (e.value.search(',') >= 1) {
window.event.keyCode = 0;
}
}
else if ((window.event.keyCode <= 45 || window.event.keyCode == 47) ||
window.event.keyCode >= 58 || window.event.keyCode == 32 || window.event.keyCode == 46) {
window.event.keyCode = 0;
}
}
else
{
if (keyCode == 44) {
if (e.value.search(',') >= 1) {
window.event.keyCode = 0;
}
}
else if ((window.event.keyCode <= 45 || window.event.keyCode == 47) ||
window.event.keyCode >= 58 || window.event.keyCode == 32 || window.event.keyCode == 46) {
window.event.keyCode = 0;
}
}
}
Exemplo da chamada da função
<asp:TextBox ID="txtValue" runat="server" onKeyPress="FormatDecimal(this)"></asp:TextBox>
Nenhum comentário:
Postar um comentário