Why not a regex ?
<input type=“text” pattern=“^$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$” />
PS: i just copy pasted the first regex I found if that one does not fill yow needs go to google a look for regex currency
Why not a regex ?
<input type=“text” pattern=“^$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$” />
PS: i just copy pasted the first regex I found if that one does not fill yow needs go to google a look for regex currency
You could alternatively also use HTML5 validation, see here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="txtChar" pattern="[d]+([.,][d]{0,2})?"
placeholder="number with max. 2 digits"
title="enter a valid currency amount #[,.]##" required><br/>
</form>
Simply enter a few test values and press return
.
you can easily specify it in the input tag to take type numbers and it will do the same of all this functions like so :-
<input type='number' name='cijenanovogtroska' id='txtChar'>
I was wondering is this ideal solution to deal with currency in Javascript?
Idea is to limit user that he can only write numbers and decimal point in input.
This code is mix of answers I found on this site and some of my own.
HTML:
<p><input type="text" class="form-control" id="cijenanovogtroska" onkeypress="return isNumberKey(event)" name="txtChar"></p>
JS File:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 46) // checks if you press dot on keyboard
{
if ($("#cijenanovogtroska:text").val().includes(".")) // that text wont include first dot, but you will limit every other try
{
return false;
}
if ($("#cijenanovogtroska:text").val() == "") // It checks if this string is empty, so dot cant go on first place
{
return false;
}
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) // numbers and dots are possible inputs
{
return false;
}
else
{
return true;
}
}
Addition to this function, in function where you have to do stuff (etc. save data to database) You would have to check that “.” is not on last position.
Is there any better implementation to do it than this?:
if (cijena.slice(-1) != ".")
{
//do stuff
}
else
{
alert("You have decimal point on last place!");
}
Thanks, I found regex for my needs
I just tried this on code snippet, but it allows me to write text
It does, but it will refuse to submit the form (press `
This works, but user can edit input field and put dots or format I dont want there. I want that to be limited so there are no mistakes in input.
if you want to save it to a database , you can specify it as number in the database . so if the user input any thing but numbers it will return error and then you can handle the error message’
I am using Google Firebase and it will just throw error without warning the user that input is not like it should be.
i didn`t use firebase before ,so good luck