CSharper CSharper - 2 months ago 21
Javascript Question

Set format for decimal number

I am validating certain input by using

RegEx
in
jQuery
which is working as expected. I want to add an addition where it adds 0 prior to decimal point if user don't add it.

For example,

.50 to 0.50
-.50 to -0.50


How to do that?

Code:



$(document).ready(function() {
$('#btnval').click(function() {
var floatRegex = new RegExp(/^-?[0-9]+([\,|\.]{0,1}[0-9]{2}){0,1}$/);
var currentSetTextBoxValue = $('#txtval').val();
//alert(currentSetTextBoxValue);
var validateInput = floatRegex.test(currentSetTextBoxValue);
alert(validateInput);
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />




Answer

Change [0-9]+ to [0-9]*, so that it allows zero digits instead of requireing at least one.

$(document).ready(function() {
  $('#btnval').click(function() {
    var floatRegex = new RegExp(/^-?[0-9]*([\,|\.]{0,1}[0-9]{2}){0,1}$/);
    var currentSetTextBoxValue = $('#txtval').val();
    //alert(currentSetTextBoxValue);
    var validateInput = floatRegex.test(currentSetTextBoxValue);
    alert(validateInput);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="txtval" />
<input type="button" value="Get textbox Value" id="btnval" />