How to block certain keys in an input using Javascript?

3

I have a function in javascript where I only allow numbers, commas (,) and hyphens (-) in an input.

The problem is that I can type as many commas (,) and hyphens (-) as I want. I would like to know how I can only allow one comma or less.

My javascript

// Somente numeros e , e -
function SomenteNumero(e) {
var tecla = (window.event) ? event.keyCode : e.which;
if ((tecla > 47 && tecla < 58 || tecla === 44 || tecla === 45 || tecla === 13))
    return true;
else {
    if (tecla === 8 || tecla === 0)
        return true;
    else
        return false;
}
}

I think so in the input:

  <input type='text' name='mg' onkeypress='return SomenteNumero(event)'>
    
asked by anonymous 22.02.2016 / 18:46

2 answers

3
  

Because the AP needs to use positive values or   negatives, I edited the answer suggesting the plugin Mask money instead of jQuery Mask - link

Mask money

Use the mask money plugin, it's even easier to use than the previous one.

Configuration Options

  • allowNegative : Allows negative values if set to true
  • prefix : adds a prefix in the input, eg R$ 9,99
  • suffix : adds a "postfix" in the input, eg 9,99 $
  • thousands : sets the thousand separator, the default separator is ,
  • decimal : sets the decimal separator, default, and .

Handling options

  • .maskMoney('destroy') : remove the element mask
  • .maskMoney('unmasked') : returns a float value without the mask, eg: ('R$ 1.234,56' => 1234.56)

There are still other options to use. See the example by applying the mask to your case.

$("#myInput").maskMoney({
  allowNegative: true,
  decimal: ',',
  thousands: '.'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>
<input id="myInput" />

jQuery Mask

This plugin - jQuery-Mask-Plugin is very easy to use and customizable. Here's an example of how you can use it.

$('#myInput').mask('000.000.000.000.000,00', {
  reverse: true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.13.4/jquery.mask.min.js"></script>
<input type="text" id="myInput" />
    
22.02.2016 / 19:11
1

You can solve this using a regular expression.

function somenteNumero(value) {
  if (/([0-9]+\,?)/.test(value)) return true;
}

Just after the asterisk you have the comma's permission. With the regular expression you assemble the rule that is needed.

    
22.02.2016 / 19:15