In Angular 7, how can I mask an input field (textbox) such that it accepts only decimal value like (8.15 or 15.25) ?
I have the following HTML input:
<input type="text" name="amount" id="amount" pattern="[0-9]+(\.[0-9][0-9]?)?" (keypress)="numbersOnly($event)">
i have following function numbersOnly which allow only decimal numbers but it should not allow to enter decimal point(.) more than one time like below.
8.155454 or 8.65.24
it should allow only 1 decimal points after number like below.
8.15 or 80.45 or 555.14
below is my function that accept only decimal value.
numbersOnly(event: any) {
let charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
You can use the keypress event to capture the input values and check in the event handler that there is only one decimal point.
I've done this by adding onkeypress="return slideNumber_keyFilter( event );" to my input element and then used this function:
<script>
function slideNumber_keyFilter( event ) {
return ( ( event.charCode >= 48 ) && ( event.charCode <= 57 ) );
}
</script>
Which in my case didn't allow for any periods, but you can simply replace the code that check the input and keep track if a period is entered, and disallow another.
Related
I'm trying to use google-libphonenumber's AsYouTypeFormatter with a simple input element on a web form. I pass each key typed by the user to the inputDigit method. The problem I'm running into is that when the user hits backspace, google-libphonenumber doesn't remove the last digit and simply appends Backspace to the phone number. Am I using the AsYouTypeFormatter improperly? Is it not able to deal with backspaces? If so, and I suspect that is the case, how should I handle the case where the user presses backspace?
Here is a link to an example project: https://stackblitz.com/edit/libphonenumber
And here is the code:
import { AsYouTypeFormatter } from 'google-libphonenumber';
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `
<h1>Libphonenumber Playground</h1>
<input id="input" type="text">
`;
this.formatter = new AsYouTypeFormatter('us');
const input = document.getElementById('input') as HTMLInputElement;
input.addEventListener('keyup', (event: KeyboardEvent) => {
console.log(this.formatter.inputDigit(event.key));
});
"isNumber": function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && (charCode < 48 || charCode > 57) || charCode === 46 || charCode === 13)) {
//do not allow non numeric characters
evt.preventDefault();
}else{
//ok: numeric character
//handle phone number masking.
this.phoneNumberForm =this.formatter.inputDigit(evt.key);
}
I haven't found any methods that will move the formatter index back.
(That doesn't mean that they are not there)
What I did was prevent the backspace keydown event. Along with any other non-numeric character. Here is the function I used:
i have the below asp.net code to get user input then using the below javascript i have make sure that it is not kept empty by the user. now what i want do is to block user input on few characters such as (|,#,#,$) using the same javascript. any suggestion on how can i do this?
<asp:TextBox ID="txtAccountName" runat="server" Width="100%" CssClass="input" Enabled="False" onblur="CheckTxtBox(this);"></asp:TextBox>
function CheckTxtBox(sender) {
if (sender.value == "") {
alert("Please enter Address 1");
return false;
}
}
Two ways you can do this
1) In "keypress" event.Check the user press a character like (|,#,#,$)then stop them right there
2) "onblur" event: when the input element loses focus, validate its contents. If the value is invalid, display a message
Note
the second method is better because if user is copy pasting the content then the first method will not catch them
First method
function CheckTxtBox(e) {
var evt = (e) ? e : window.event;
var charCode = (evt.keyCode) ? evt.keyCode : evt.which;
if (//charactercode of the keys as condition) {
return false;
}
return true;
};
Second Method
In your onblur event you can check your textbox value with a regular expression and validate it with regular expression.
function CheckTxtBox(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
An your asp control :
<asp:TextBox ID="txtAccountName" runat="server" Width="100%" CssClass="input" Enabled="False" onkeypress="return CheckTxtBox(event)""></asp:TextBox>
To validate keys/text entered in edit controls, Regular Expressions are recommended. Have a look at: http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html for demos on few such validation examples.
But, it is not a good practice to stop the validation with the browser alone. Always do a validation at the server end. This is due to the fact that JavaScript can be disabled in browsers, which can allow non-validated data posts to the server.
i did it here is what i did. now this takes only uppercase charters from (A-Z) and numbers from (1-9). thank everyone for your help. its much appreciated.
<asp:TextBox ID="txtAccountName" runat="server"
Width="100%" CssClass="input" Enabled="False" onkeypress="return isNumber(event);"></asp:TextBox>
// this JS validates and prevent inputting symbols
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
Hi i have a function which accepts numbers but there's a few problems with it.
1) i want it to accept slashes i.e. '/'?
2) On the first input it accepts letters for some reason.
it binded to a knockout keyup function.
<input id="txtboxToFilter" type="text" placeholder="dd/mm/yyyy" maxlength="10" data-bind="value: Observable.birthdate(), valueUpdate: 'keyup', event: { keyup: CheckDate}" />
Which then calls this function.
function CheckDate(){
document.getElementById('txtboxToFilter').onkeydown = function(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
}
Any body help?
You can certainly use Regex:
here is one which will support leap years as well :)
^(?:(?:31(\/)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
JS code:
document.getElementById('txtboxToFilter').onblur= function(e) {
alert(validateDate(document.getElementById('txtboxToFilter').value));
}
function validateDate(dob) {
var re = /^(?:(?:31(\/)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/;
return re.test(dob);
}
fiddle: http://jsfiddle.net/exe0m3ek/
NOTE: I have changed the event from keyup to blur, If you only want
this on keyup...please change accordingly.
I want to avoid the min value 0 for my input type.
I am using following jquery but it allows to enter 0.
$('input.numeric').bind('keypress', function (e) {
return (e.which != 8 && e.which > 0 && (e.which < 48 || e.which > 57)) ? false : true;
})
I tried to make it with html-5 setting attribute type="number" but unfortunately mozila does not support it.
I just want my input type to accept the numeric other grater than 0, not decimal at all or any thing else.
By refactoring your return statement, with a direct and more readable way, you can get something like this:
$('input.numeric').bind('keypress', function (e) {
return (e.which > 48 && e.which <= 57) // If it's a number between 1 and 9
|| (e.which == 48 && $(this).val() != "") // Or 0 and the field isn't empty
|| e.which == 8; // Or backspace
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Type a number: <input class="numeric" type="text" />
Be aware this validation doesn't allow the user to use directional arrow in your field though... And a server-side verification is always mandatory, since the user can disable JS. Even though Firefox does not support it, you should use type="number".
You could also do this;
<input type='number' min='1'>
EDIT
$("input.numeric").focusout(function() {
if($("input.numeric").val() < 1){
$("input.numeric").val(1);
}
});
I'm using the commonly used Javascript function to allow only numbers to be inputted into a text field:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
I call this onkeypress and it prevents anything but numbers to display. I'm trying to alter it so it will allow me to also put dashes (-) into the text field. The dash keycode is 189 so I tried this:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode != 189 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
Thinking that the conditional statement would then accept the dash character but that didn't seem to work. Any ideas on why this would be? Thanks for your help!
If you're using the keypress event you need to use the character code 45 for dash/hyphen.
If you're using the keydown/keyup events then you need to use 109 and 189 to cover the minus key in the numeric keypad and the one (usually) located above the P key.
if (charCode != 46 && charCode != 45 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
Demo: http://jsfiddle.net/J6B7U/
If you have doubts about which keycode is which a console.log(charCode); in your function will help you debug.
(Note also that trapping a key event is not enough to prevent invalid data being entered, because the user may change the field using the browser's edit menu or drag'n'drop.)
try this
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 45 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
in html
<input type="text" onkeypress="return isNumberKey(event)">
You want to use the character code for the dash, which is 45, not the keycode.
this code for only number types
<input onkeypress="return isNumberKey(event);">
<script>
function isNumberKey(evt)
{
var t = (evt.which) ? evt.which : event.keyCode;
return !(t > 31 && (t < 48 || t > 57))
}
</script>
This came up when I was asking, so it might be worth adding here that keyCode and charCode are deprecated, as at this time.
A better way of adding the check or implementing an isNumberKey function that also accepts the '-' character could be:
const isNumberKey = (event: KeyboardEvent) =>
((event.key.length > 1) || event.key.match(/^\d|-$/))
This way, we check allow special keys do their function, while making sure only numbers are allowed when single character keys are pressed.
This doesn't work well with mobile devices. For example, Chrome on Android will bring up the number keypad rather than the full keyboard when the input type is set to "number". You could try using input type="tel" instead. It would allow numbers 0-9, the - and (). It would also bring up the dial pad on Android. Haven't tested on iPhone.