Force input with a dot instead of an html comma

Asked

Viewed 4,789 times

0

In the table the price field has the Decimal data type, where the input is this way:

<p><h5><strong>Preço</strong></h5> <input type="text" id="Preco" name="Preco" size="120" /><br/></p>

But I input the product and the price, if put the value with comma does not enter in the database.

I intend to force the fill with the dot, if put the comma give a message warn that you have to use the dot.

7 answers

2

It is not good practice to restrict the user.

Let him put what he wants and make you this validation:

<input input type="text" id="Preco" name="Preco" size="120" onchange="this.value = this.value.replace(/,/g, '.')"/>
  • Thank you.... It worked

1

I have a simple solution for you friend, do not limit yourself to the point or comma, you should think about the user experience with your platform. There is a lib calling for Mask js, it serves to create masks in your input and leaves you with a friendlier formatting. The only thing you need to do is care about her and the jquery before it. Use is basic.

For implementation you have two options, data-attribute html, or in js even.

// html    
<input type="text" name="preco" data-mask="#.##0,00" />

// js        
$('input[name='preco']').mask("#.##0,00", {
        reverse: true
      });

Using this your price field will have a user-friendly money formatting. But the format will be invalid to save in the bank, to solve this problem, I will provide a function for you, who converts this price with this format to save in the bank, and vice versa.

function formattedPriceForDB($price) { // formata pra salvar no banco
    $source = array('.', ',');
    $replace = array('', '.');
    $valor = str_replace($source, $replace, $price); //remove os pontos e substitui a virgula pelo ponto
    return $valor; //retorna o valor formatado para gravar no banco
}

function formattedPrinceForBr($price) { // formata pra mostrar ao usuário
        return number_format($price, 2, ',', '.');
    }

If you prefer to receive only points use this code:

$("form").submit(function(e){
  e.preventDefault();
  if($("#preco").val().indexOf(",") != -1){
    $("span").text("erro ! retire as virgulas e coloque pontos");
  } else {
    $("span").text("tudo certo");
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<input type="text" name="preco" id="preco"/> <br/>
<input type="submit" value="enviar"/>
<span></span>
</form>

1

That script with jQuery does what you’re asking:

$(document).on("keyup", '.preco', function (e) {
    if (e.keyCode == 188 || e.keyCode == 108) { // KeyCode For comma is 188
        alert('Use ponto');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<p><h5><strong>Preço</strong></h5> <input type="text" id="Preco" class="preco" name="Preco" size="120" /><br/></p>

Now if you want something more advanced look below:

/*
 *
 * Copyright (c) 2006-2011 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Version 1.3.1
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 *
 */
(function($) {
/*
 * Allows only valid characters to be entered into input boxes.
 * Note: fixes value when pasting via Ctrl+V, but not when using the mouse to paste
  *      side-effect: Ctrl+A does not work, though you can still use the mouse to select (or double-click to select all)
 *
 * @name     numeric
 * @param    config      { decimal : "." , negative : true }
 * @param    callback     A function that runs if the number is not valid (fires onblur)
 * @author   Sam Collett (http://www.texotela.co.uk)
 * @example  $(".numeric").numeric();
 * @example  $(".numeric").numeric(","); // use , as separator
 * @example  $(".numeric").numeric({ decimal : "," }); // use , as separator
 * @example  $(".numeric").numeric({ negative : false }); // do not allow negative values
 * @example  $(".numeric").numeric(null, callback); // use default values, pass on the 'callback' function
 * @example  $(".numeric").numeric({ scale: 2 }); // allow only two numbers after the decimal point.
 * @example  $(".numeric").numeric({ scale: 0 }); // Same as $(".numeric").numeric({ decimal : false });
 * @example  $(".numeric").numeric({ precision: 2 }); // allow only two numbers.
 * @example  $(".numeric").numeric({ precision: 4, scale: 2 }); // allow four numbers with two decimals. (99.99)
 *
 */
$.fn.numeric = function(config, callback)
{
	if(typeof config === 'boolean')
	{
		config = { decimal: config };
	}
	config = config || {};
	// if config.negative undefined, set to true (default is to allow negative numbers)
	if(typeof config.negative == "undefined") { config.negative = true; }
	// set decimal point
	var decimal = (config.decimal === false) ? "" : config.decimal || ".";
	// allow negatives
	var negative = (config.negative === true) ? true : false;
	// callback function
	callback = (typeof(callback) == "function" ? callback : function() {});
	// scale
	var scale;
	if ((typeof config.scale) == "number")
	{
		if (config.scale == 0)
		{
			decimal = false;
			scale = -1;
		}
		else
			scale = config.scale;
	}
	else
		scale = -1;
	// precision
	var precision;
	if ((typeof config.precision) == "number")
	{
		precision = config.precision;
	}
	else
		precision = 0;
	// set data and methods
	return this.data("numeric.decimal", decimal).data("numeric.negative", negative).data("numeric.callback", callback).data("numeric.scale", scale).data("numeric.precision", precision).keypress($.fn.numeric.keypress).keyup($.fn.numeric.keyup).blur($.fn.numeric.blur);
};

$.fn.numeric.keypress = function(e)
{
	// get decimal character and determine if negatives are allowed
	var decimal = $.data(this, "numeric.decimal");
	var negative = $.data(this, "numeric.negative");
	// get the key that was pressed
	var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
	// allow enter/return key (only when in an input box)
	if(key == 13 && this.nodeName.toLowerCase() == "input")
	{
		return true;
	}
	else if(key == 13)
	{
		return false;
	}
	var allow = false;
	// allow Ctrl+A
	if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) { return true; }
	// allow Ctrl+X (cut)
	if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) { return true; }
	// allow Ctrl+C (copy)
	if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) { return true; }
	// allow Ctrl+Z (undo)
	if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) { return true; }
	// allow or deny Ctrl+V (paste), Shift+Ins
	if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */ ||
	  (e.shiftKey && key == 45)) { return true; }
	// if a number was not pressed
	if(key < 48 || key > 57)
	{
	  var value = $(this).val();
		/* '-' only allowed at start and if negative numbers allowed */
		if(value.indexOf("-") !== 0 && negative && key == 45 && (value.length === 0 || parseInt($.fn.getSelectionStart(this), 10) === 0)) { return true; }
		/* only one decimal separator allowed */
		if(decimal && key == decimal.charCodeAt(0) && value.indexOf(decimal) != -1)
		{
			allow = false;
		}
		// check for other keys that have special purposes
		if(
			key != 8 /* backspace */ &&
			key != 9 /* tab */ &&
			key != 13 /* enter */ &&
			key != 35 /* end */ &&
			key != 36 /* home */ &&
			key != 37 /* left */ &&
			key != 39 /* right */ &&
			key != 46 /* del */
		)
		{
			allow = false;
		}
		else
		{
			// for detecting special keys (listed above)
			// IE does not support 'charCode' and ignores them in keypress anyway
			if(typeof e.charCode != "undefined")
			{
				// special keys have 'keyCode' and 'which' the same (e.g. backspace)
				if(e.keyCode == e.which && e.which !== 0)
				{
					allow = true;
					// . and delete share the same code, don't allow . (will be set to true later if it is the decimal point)
					if(e.which == 46) { allow = false; }
				}
				// or keyCode != 0 and 'charCode'/'which' = 0
				else if(e.keyCode !== 0 && e.charCode === 0 && e.which === 0)
				{
					allow = true;
				}
			}
		}
		// if key pressed is the decimal and it is not already in the field
		if(decimal && key == decimal.charCodeAt(0))
		{
			if(value.indexOf(decimal) == -1)
			{
				allow = true;
			}
			else
			{
				allow = false;
			}
		}
	}
	//if a number key was pressed.
	else
	{
		// If scale >= 0, make sure there's only <scale> characters
		// after the decimal point.
		if($.data(this, "numeric.scale") >= 0)
		{
			var decimalPosition = this.value.indexOf(decimal);
			//If there is a decimal.
			if (decimalPosition >= 0)
			{
				decimalsQuantity = this.value.length - decimalPosition - 1;
				//If the cursor is after the decimal.
				if ($.fn.getSelectionStart(this) > decimalPosition)
					allow = decimalsQuantity < $.data(this, "numeric.scale");
				else
				{
					integersQuantity = (this.value.length - 1) - decimalsQuantity;
					//If precision > 0, integers and decimals quantity should not be greater than precision
					if (integersQuantity < ($.data(this, "numeric.precision") - $.data(this, "numeric.scale")))
						allow = true;
					else
						allow = false;
				}
			}
			//If there is no decimal
			else {
				if ($.data(this, "numeric.precision") > 0)
					allow = this.value.replace($.data(this, "numeric.decimal"), "").length < $.data(this, "numeric.precision") - $.data(this, "numeric.scale");
				else
					allow = true;
			}
		}
		else
			// If precision > 0, make sure there's not more digits than precision
			if ($.data(this, "numeric.precision") > 0)
				allow = this.value.replace($.data(this, "numeric.decimal"), "").length < $.data(this, "numeric.precision");
			else
				allow = true;
		}
	return allow;
};

$.fn.numeric.keyup = function(e)
{
	var val = $(this).val();
	if(val && val.length > 0)
	{
		// get carat (cursor) position
		var carat = $.fn.getSelectionStart(this);
		// get decimal character and determine if negatives are allowed
		var decimal = $.data(this, "numeric.decimal");
		var negative = $.data(this, "numeric.negative");
		
		// prepend a 0 if necessary
		if(decimal !== "" && decimal !== null)
		{
			// find decimal point
			var dot = val.indexOf(decimal);
			// if dot at start, add 0 before
			if(dot === 0)
			{
				this.value = "0" + val;
			}
			// if dot at position 1, check if there is a - symbol before it
			if(dot == 1 && val.charAt(0) == "-")
			{
				this.value = "-0" + val.substring(1);
			}
			val = this.value;
		}
		
		// if pasted in, only allow the following characters
		var validChars = [0,1,2,3,4,5,6,7,8,9,'-',decimal];
		// get length of the value (to loop through)
		var length = val.length;
		// loop backwards (to prevent going out of bounds)
		for(var i = length - 1; i >= 0; i--)
		{
			var ch = val.charAt(i);
			// remove '-' if it is in the wrong place
			if(i !== 0 && ch == "-")
			{
				val = val.substring(0, i) + val.substring(i + 1);
			}
			// remove character if it is at the start, a '-' and negatives aren't allowed
			else if(i === 0 && !negative && ch == "-")
			{
				val = val.substring(1);
			}
			var validChar = false;
			// loop through validChars
			for(var j = 0; j < validChars.length; j++)
			{
				// if it is valid, break out the loop
				if(ch == validChars[j])
				{
					validChar = true;
					break;
				}
			}
			// if not a valid character, or a space, remove
			if(!validChar || ch == " ")
			{
				val = val.substring(0, i) + val.substring(i + 1);
			}
		}
		// remove extra decimal characters
		var firstDecimal = val.indexOf(decimal);
		if(firstDecimal > 0)
		{
			for(var k = length - 1; k > firstDecimal; k--)
			{
				var chch = val.charAt(k);
				// remove decimal character
				if(chch == decimal)
				{
					val = val.substring(0, k) + val.substring(k + 1);
				}
			}
			// remove numbers after the decimal so that scale matches.
			if ($.data(this, "numeric.scale") >= 0)
				val = val.substring(0, firstDecimal+$.data(this, "numeric.scale") + 1);
			// remove numbers so that precision matches.
			if ($.data(this, "numeric.precision") > 0)
				val = val.substring(0, $.data(this, "numeric.precision") + 1);
		}
		// limite the integers quantity, necessary when user delete decimal separator
		else if ($.data(this, "numeric.precision") > 0)
			val = val.substring(0, ($.data(this, "numeric.precision") - $.data(this, "numeric.scale")));
		
		// set the value and prevent the cursor moving to the end
		this.value = val;
		$.fn.setSelection(this, carat);
	}
};

$.fn.numeric.blur = function()
{
	var decimal = $.data(this, "numeric.decimal");
	var callback = $.data(this, "numeric.callback");
	var val = this.value;
	if(val !== "")
	{
		var re = new RegExp("^\\d+$|^\\d*" + decimal + "\\d+$");
		if(!re.exec(val))
		{
			callback.apply(this);
		}
	}
};

$.fn.removeNumeric = function()
{
	return this.data("numeric.decimal", null).data("numeric.negative", null).data("numeric.callback", null).unbind("keypress", $.fn.numeric.keypress).unbind("blur", $.fn.numeric.blur);
};

// Based on code from http://javascript.nwbox.com/cursor_position/ (Diego Perini <[email protected]>)
$.fn.getSelectionStart = function(o)
{
	if (o.createTextRange)
	{
		var r = document.selection.createRange().duplicate();
		r.moveEnd('character', o.value.length);
		if (r.text === '') { return o.value.length; }
		return o.value.lastIndexOf(r.text);
	} else { return o.selectionStart; }
};

// set the selection, o is the object (input), p is the position ([start, end] or just start)
$.fn.setSelection = function(o, p)
{
	// if p is number, start and end are the same
	if(typeof p == "number") { p = [p, p]; }
	// only set if p is an array of length 2
	if(p && p.constructor == Array && p.length == 2)
	{
		if (o.createTextRange)
		{
			var r = o.createTextRange();
			r.collapse(true);
			r.moveStart('character', p[0]);
			r.moveEnd('character', p[1]);
			r.select();
		}
		else if(o.setSelectionRange)
		{
			o.focus();
			o.setSelectionRange(p[0], p[1]);
		}
	}
};

})(jQuery);

$(".numeric").numeric({ decimal : ".",  negative : false, scale: 3 });

$(document).on("keyup", '.numeric', function (e) {
    if (e.keyCode == 188 || e.keyCode == 108) { // KeyCode For comma is 188
        alert('Use ponto 10.00');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Preço
<input class="numeric" type="text" />

Code taken from: https://jsfiddle.net/vandalo/fhYAs/

  • The first example you put me, the simplest, here I do run and it works, on my page does not show the message to put the point or to force the user to put the point

1

You can use the tag pattern of html, see;

<form action="#">
<label for="price">Preço:</label> 
<input type="text" 
        name="price" 
        pattern="[0-9]\.[0-9]"
        title="casa decimal deve ser separada por ponto"
/>
<button type="submit">Enviar</button>
</form>

See versions of browsers that support the tag pattern:

  • Chrome: 5.0+
  • Edge 10.00+
  • Firefox: 4.0+
  • Safari: 10.1+
  • Opera 9.6+

For more information, see page of w3cschool about the tag pattern

  • But with this example it accepts neither commas nor dots, says to fill in with the requested format

  • @Junior sorry, I forgot to include the tag title.

1


Look, if you’re working with pennies, you can use JQuery with that system:

Jquery Mask Money

Include both *.JS in the header of the HTML, then create the function that will check, it will not only prevent you to use comma, but will insert the point automatically.

The user will only have to enter numbers without having to worry about pressing another button.

$(function() {
  $('#Preco').maskMoney({ decimal: '.', thousands: '', precision: 2 });
})
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>
</head>
<body>
  <input type="text" id="Preco" value="0.00" />
</body>

0

There are several solutions to your problem.

  • HTML (caution, compatibility problems between browsers)

You can use a different type of input (number instead of text), so the user will not be able to enter commas (only points). In Mozilla Firefox, the following code is sufficient, however for other browsers you may have to add the attribute step="any" to work with non-integer numbers.

<input type="number" id="Preco" name="Preco" size="120" />

  • Javascript (client side)

Or you can use Javascript (jQuery here) to turn the commas into dots, for example: $(this).val($(this).val.replace(',', '.'));

that you can run in the "onchange" event for example. If you prefer to keep this transformation hidden from the user, use this function only when the form is submitted (Submit event).

  • PHP (server side)

Or you can do this in PHP:

$preco = $_POST['Preco']; $preco = str_replace(",", ".", $preco);

You can check that the entered value is a number with this function (PHP) as well:

if (!is_numeric($preco)) { // tem um erro! }


It is worth remembering that it is necessary to do the checks on the server anyway, since the user can modify the code that is on his machine (client side).

  • The type="number" let use no comma or dots, only whole numbers

  • Sorry, I’m using Firefox and it accepts points. Chrome won’t let me. I’ll edit my answer.

  • Apparently only previous versions of Chrome did not leave without the attribute "step", but now works without anything (since version 43 at least). I would have to do more research to find out about other browsers. (I imagine IE has its own rules...)

0

@Junior, use the MeioMask to the front:

https://github.com/fabiomcosta/jquery-meiomask

It is very easy to use:

<script type="text/javascript">
$(document).ready(function(){
    $('#Preco').setMask({
        mask: '99,999.99', type: 'reverse'
    });
});
</script>

In this JS above, you force the user to type the decimal place with comma and the thousand separator with dot.

Then in PHP you do the following cleaning before putting in your Query:

<?php $Preco = $str_replace(array('.',','),array('','.'),$_POST['Preco']); ?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.