Javascript - validation, numbers only - javascript

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
Part of the Login
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}

Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
Edit:
RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.
Simply omit the negating ! and use if(/\D/.test(z)).

here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers

This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}

Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
Validate numbers in JavaScript - IsNumeric()

function validateNumber(e) {
const pattern = /^[0-9]$/;
return pattern.test(e.key )
}
<input name="username" id="username" onkeypress="return validateNumber(event)">
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc

The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.

No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
Javascript Approach
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery Approach
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
The above answers are for most common use case - validating input as a number.
But to allow few special cases like
negative numbers & showing the invalid keystrokes to user before
removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};

function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.

I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >

Using the form you already have:
var input = document.querySelector('form[name=myForm] #username');
input.onkeyup = function() {
var patterns = /[^0-9]/g;
var caretPos = this.selectionStart;
this.value = input.value.replace(patterns, '');
this.setSelectionRange(caretPos, caretPos);
}
This will delete all non-digits after the key is released.

var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
elem[i].addEventListener('keypress', function(event){
var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
var validIndex = keys.indexOf(event.charCode);
if(validIndex == -1){
event.preventDefault();
}
});
}

If you are using React, just do:
<input
value={this.state.input}
placeholder="Enter a number"
onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
state = {
input: '',
}
onChange = e => {
let input = e.target.value.replace(/[^0-9]/g, '');
this.setState({ input });
}
render() {
return (
<div>
<input
value={this.state.input}
placeholder="Enter a number"
onChange={this.onChange}
/>
<br />
<h1>{this.state.input}</h1>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
</script>

// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:
$(document).ready(function () {
$(".nosonly").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
alert("Only Numbers Allowed"),event.preventDefault();
}
}
});
});

Avoid symbols like "." "," "+" "-". I tried it and it works fine.
$('#example').keypress(function (evt) {
if (evt != null && evt.originalEvent != null && /\D/.test(evt.originalEvent.key)) {
evt.preventDefault();
evt.stopImmediatePropagation();
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="example" id="example">

Related

Querying input text with javascript and checking for a value does not work

I would like to query an input field with Javascript and from a value of over 20 a button should be released. Javascript works too. Unfortunately, if I enter the number with a comma instead of a period, it no longer works.
var checkEmpty_ek = document.querySelector('#ek');
checkEmpty_ek.addEventListener('input', function() {
if (checkEmpty_ek.value >= 20) {
document.getElementById("neuerbuttonspeichern").disabled = false;
} else {
document.getElementById("neuerbuttonspeichern").disabled = true;
}
});
<input type="text" id="ek" name="ek" value="$ek">
<input type="button" id="neuerbuttonspeichern" value="Send" />
Try: let inputValue = Number(checkEmpty_ek.value.replace(",",".")); inside function.
And then check: (inputValue >= 20)
It is not the most elegant solution, but it will resolve if the user types the number with a comma or with letters and special characters.
Bye.
Use type = number
var checkEmpty_ek = document.querySelector('#ek');
checkEmpty_ek.addEventListener('input', function() {
document.getElementById("neuerbuttonspeichern").disabled = checkEmpty_ek.value < 20;
});
$ek<input type="number" id="ek" name="ek" value="0">
<input type="button" id="neuerbuttonspeichern" value="Send" disabled />
if (Number(checkEmpty_ek.value.replace(/,/g, '')) >= 20) {
{
document.getElementById("neuerbuttonspeichern").disabled = false;
} else
{
document.getElementById("neuerbuttonspeichern").disabled = true;
});
If you are just looking to remove any potential commas from the input, this will do it. But like someone else commented, we aren't really familiar with your user interaction expectations. Chances are, you'll be filtering out more than commas.
Just replace the comma with the dot.
Number(checkEmpty_ek.value.replace(",","."))
Number ("20.") === 20
var checkEmpty_ek = document.querySelector('#ek');
checkEmpty_ek.addEventListener('input', function() {
console.log(checkEmpty_ek.value)
if (Number(checkEmpty_ek.value.replace(",",".")) >= 20) {
document.getElementById("neuerbuttonspeichern").disabled = false;
} else {
document.getElementById("neuerbuttonspeichern").disabled = true;
}
});
<input type="text" id="ek" name="ek" value="">
<input type="button" id="neuerbuttonspeichern" value="Send" />

How to allow only digits to be entered into an input[type="number"] field?

I have an input field in which the user should only be able to enter digits [0-9].
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = this.value.replace(/[^\d]/g, '');
}
<input type="number" id="integer" />
jsFiddle Demo
The problem is this: When I enter a number (eg. 1234) and then press dot (.), + or - the content of the input field is automatically deleted by the browser (value is set to "" = empty string). But why? Changing the type from number to text seems to fix the problem. But then I lose the up/down arrow functionality of the input field. Any ideas?
HTML 4 has an event called onkeypress. With that attribute we can do this without using additional JS:
<input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">
Here digits from 0 to 9 are allowed using the event.charCode from 48 to 57.
I think the reason that the browser clean the input value it is because a string with two dots it is not a number.
Some corrections about your code:
You need to change your expression regular if you want to accept number with decimal part. Now, you are only express that you want to accept digits [0-9] and no more chars.
To accomplish want you want, you need to change /[^\d]/g to /[^\d.]/g.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger()
{
this.value = this.value.replace(/[^\d.]/g, '');
}
<input type="number" id="integer" />
HOWEVER: If you define your input as number type, the regular expression is not needed. So, you just need to define the input like this and should your to your case:
<input type="number" id="integer" />
[THE SOLUTION]
To fully meet your needs, I came with a solution that catch the keydown event of the input and check if there is any '.' on the input. If yes, I prevent the char to go to the input.
document.getElementById("integer").addEventListener('keydown', restrictToInteger);
var lastCodeWasDot = false;
function restrictToInteger(e)
{
var inputValue = document.getElementById("integer").value;
var isDot = false;
var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.charCode == 190);
console.log(e.keyCode);
if(isDot && (inputValue.indexOf(".") > -1 || inputValue == "" || lastCodeWasDot)) {
e.preventDefault();
}
lastCodeWasDot = isDot;
}
<input type="number" id="integer" />
Explaning the solution:
The line of code var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.keyCode == 190) || false; is needed because cross browser compatibility.
I don't now why but if you try to get the value from an input number type in the firefox, and if the value finishes with a dot, the value that you will get will be without the last dot of the input. To fix that, I needed to add the variable lastCodeWasDot to fix this issue.
NOTE: The number input can accept floating point numbers, including negative symbols and the e or E character (check out this post)
Based on the answers of Alexandru-Ionut Mihai and natchiketa I created the following solution:
document.getElementById("integer").addEventListener("input", allowOnlyDigits);
function allowOnlyDigits() {
if (this.validity.valid) {
this.setAttribute('current-value', this.value.replace(/[^\d]/g, ""));
}
this.value = this.getAttribute('current-value');
}
<input type="number" id="integer" />
On input the value is checked for validity. If it is valid, all non-digits are removed and the value is stored in a custom attribute of the element. If the value is not valid, the previous value is restored.
Notes:
The RegEx-replace is required only for Internet Explorer as it allows you to enter , or . at the end of a number.
Tested in IE, Edge, Chrome and Firefox
Chrome still allows you to enter a + before and one , after the number.
I found one issue: If you initialize the field with a value, the value is lost when you first hit an invalid char on the keyboard.
Another issue: You can't enter a negative number.
The only problem was your input type. Change it to text and it should work !
function validate(e) {
var charCode = e.keyCode? e.keyCode : e.charCode
if (!(charCode >= 48 && charCode <= 57)) {
if(!(charCode>=37 && charCode<=40))
if(charCode!=8 && charCode!=46)
return false;
}
}
<input type="number" id="integer" pattern="[0-9]"
onkeydown="return validate(event)"/>
You can achieve your requirement by copying the old value of input and using setAttribute and getAttribute methods in order to store the values.
function myFunction(input){
input.setAttribute('current-value',"");
input.oninput=function(){
let currentValue=input.getAttribute('current-value');
if(input.value!='' || (currentValue>=1 && currentValue<=9))
input.setAttribute('current-value',input.value);
input.value=input.getAttribute('current-value');
}
}
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
When you call oninput, the <input> element first calls its internal methods to handle the value. This prevents your function from seeing any actual erroneous characters, namely e+-. - all used by JavaScript to format numbers.
You can see this by adding console.log calls before and after changing this.value.
console.log(this.value);
this.value=this.value.replace(/[^\d]/g, '');
console.log(this.value);
There is never any difference!
If you try, for example:
console.log(this.value);
this.value+=1; // or *=2 for numerical fun
console.log(this.value);
you can see a difference.
So your function is hastening the normal internal calls <input type='number'/> would normally make when handling illegal input.
Can't quite see why the field is left blank and not 1 though.
I would switch to a cancelable event like keydown.
That way you can prevent the character from being typed in the first place:
var cancelEvent = function (e) {
e.preventDefault();
return false;
},
restrictToInteger = function restrictToInteger(e) {
var acceptableInput = /[0-9]/g,
clipboardKeys = /[zxcv]/ig,
field = e.key || e.char,
isClipboardOperation = (clipboardKeys.test(field) && e.ctrlKey),
inputIsAcceptable = field ? (
acceptableInput.test(field)
|| field.length > 1
|| isClipboardOperation
) : true;
if (!inputIsAcceptable) {
cancelEvent(e);
}
},
ensureIntegerValueOnPaste = function ensureIntegerValueOnPaste(e) {
var data = e.clipboardData || e.dataTransfer,
text = data.getData('text'),
int = parseInt(this.value + text, 10);
if (isNaN(int)) {
cancelEvent(e);
} else {
window.setTimeout(function () {
e.target.value = int;
}, 0);
}
},
input = document.getElementById("integer");
input.addEventListener('keydown', restrictToInteger);
input.addEventListener('drop', ensureIntegerValueOnPaste);
input.addEventListener('paste', ensureIntegerValueOnPaste);
<input type="number" id="integer" />
Updated fiddle: https://jsfiddle.net/838pa8hv/2/
Disclaimers:
Only tested in Chrome.
The test for field.length > 1 is to catch non-numeric keys that are valid as the up/down arrows have a value of ArrowUp and ArrowDown respectively. This also allows for keys like Shift (or Home, Backspace, Delete, etc.) to be pressed as well.
Edit:
To handle pastes (and drops), you can do the same thing in those respective events. Updated fiddle and code snippet above.
Edit:
If the expected usability is to be able to paste/drop partial numbers into the field and to not allow negative integers, then you can just change how int is defined in the ensureIntegerValueOnPaste function. Updated fiddle and code snippet above.
You don't need regular expression, you can use parseFloat() function. Your input type remains unchanged, there are still "arrows" to increase/decrease number and also it makes sure that your input will not start with zero.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = parseFloat(this.value);
}
<input type="number" id="integer" />
You have to check if the value is not a number and then stop user.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger(e)
{
if(isNaN(e.data)){
alert("only numbers allowed");
}
}
<input type="number" id="integer" />

How can I use JQuery to add a decimal and trailing zeros to currency?

I have checked all related questions and none, fully address my question. I know how to convert to money with symbols and commas, but not sure how to add trailing zeros if the user did not specify cents.
I did come across a post that mentioned adding this .toFixed(2) but I do not understand how to incorporate that into my function.
Desired function is 14578 to convert to $14,578.00 but do not add the zeros if the number were 14578.79 to $14,578.79. Also I noticed that it puts a dollar sign in the field even if left blank. Any way to avoid that?
$('.money').blur(function(e){
$(this).val(formatCurrency(this.value.replace(/[,$]/g,'')));
}).on('keypress',function(e){
if(!$.isNumeric(String.fromCharCode(e.which))) e.preventDefault();
}).on('paste', function(e){
var cb = e.originalEvent.clipboardData || window.clipboardData;
if(!$.isNumeric(cb.getData('text'))) e.preventDefault();
});
function formatCurrency(number){
var n = number.split('').reverse().join("");
var n2 = n.replace(/\d\d\d(?!$)/g, "$&,");
return '$' + n2.split('').reverse().join('');
}
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class="money"/>
<input type='text'/>
<input type='text' class="money"/>
<input type='text'/>
<input type='text' class="money"/>
<input type='text'/>
<input type='text' class="money"/>
<input type='text'/>
Thank you!
To prevent inserting empty "$" you need to check if number is empty and return the function. Here's a solution for you. You also need to allow "." in your keypress to allow users to add cents.
$('.money').blur(function(e){
if($(this).val() == "") return;
$(this).val(formatCurrency(this.value.replace(/[,$]/g,'')));
}).on('keypress',function(e){
if(String.fromCharCode(e.which) != "." && !$.isNumeric(String.fromCharCode(e.which))) e.preventDefault();
}).on('paste', function(e){
var cb = e.originalEvent.clipboardData || window.clipboardData;
if(!$.isNumeric(cb.getData('text'))) e.preventDefault();
});
function formatCurrency(number){
if(number == "") return;
number = parseFloat(number).toFixed(2);
var n = number.split('').reverse().join("");
console.log(n);
var n2 = n.replace(/\d\d\d(?!$)/g, "$&,");
return '$' + n2.split('').reverse().join('');
}
Check jsFiddle here: https://jsfiddle.net/7scapsk9/
parseFloat(value).toFixed(n)
Where value is your number (can be string) and n is the number of decimals to show
Replace your current formatCurrency function with this one:
function formatCurrency(number) {
return (number != null && number != "") ? "$".concat(parseFloat(number).toFixed(2).toString()
.split('').reverse().join("")
.replace(/\d\d\d(?!$)/g, "$&,")
.split('').reverse().join("")) : number;
}
If the number (or string that's a number) that's passed in isn't null, undefined, or an empty string it will parse the number into valid currency.

Allow only letters on a text field to be displayed

i have this jquery function
$('#contact_name').on('input', function() {
var input=$(this);
var re =/^[A-Za-z]+$/;
var is_email=re.test(input.val());
if(is_email)
{
}
else
{
}
});
for this text field
<label for="contact_name">Name:</label>
<input type="text" id="contact_Name" name="name"></input>
what i want is when the user types a number not letter i don't want the number to be displayed on the text field .. the text field only take letters and allow letters to be displayed on it and if it's a letter then display it .. so the user can know that this text field doesn't take numbers
how to do it ??
You may try this example
html
<input type="text" placeholder="Only letters" id="contact_name"/>
script
$(function()
{
$("#contact_name").on('input', function()
{
this.value=this.value.replace(/[^a-zA-Z]/g,'');
});
});
use this function
function chkLetter(event) {
var v= event.keyCode;
return ((v>= 65 && v<= 90) || v== 8);
};
you can try this way
<script type="text/javascript">
function CheckValue(e){
e=(window.event) ? event : e;
return (/[A-Za-z]/.test(String.fromCharCode(e.keyCode)));
}
</script>
<input type="text" onkeydown="return CheckValue(event)">

Javascript or jQuery to accept numbers less than 100 for text field

In my project I have a text field where I need to accept values less than or equal to 100. In that text field how can I achieve this through javascript or jquery. Somehow I have managed to accept only numbers in text box but how can i restrict it not accept numbers greater than 100.
Here is the code which I have tried to accept only numbers
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
First off, you can use number type in HTML5 with the max attribute set to 100.
<input id="numberbox" type='number' max='100'>
This will allow your browser to detect when it's over 100 when submitted. However, it won't work on older browsers and some smartphones.
Alternatively, you could do this:
<input type='text' maxlength='2' pattern='^[0-9]$'>
But I feel this option is overkill. But if you want to do it that way, that's up to you.
In jQuery, you can do this:
$('#numberbox').keyup(function(){
if ($(this).val() > 100){
alert("No numbers above 100");
$(this).val('100');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='numberbox'>
Please also validate back-end, someone with only just enough knowledge could easily bypass this.
Check this demo
Also you have to restrict the length of text field
Something like this
var fieldVal = document.getElementById('txtF').value;
//Suppose u want number that is less than 100
if(fieldVal < 100){
return true;
}
else
{
//
}
With jquery you can to something like this :
$('#my-field').blur(function() {
if(parseInt($(this).val()) < 100) {
$(this).val('');
}
});
The blur event is thrown when user leave the field (field loose the focus). Then it chekcks if the value is less than 100 and empty it if necessary.
along with your code you can add one more line to restrict text-field to accept less than 2 char....
if (charCode.length > 2) {
return false;
}
You can do this:
$('yourElem').on('keydown', function(e){
if(this.value > 100){
alert('You have entered more than 100 as input');
return false;
}
});
maxlength attribute can restrict the numbers more than 3 digits, so you can use this to restrict:
maxlength="3"
yet you need to do js validation as suggested above because user with maxlength still can enter more than 100 as asked.
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
var str = String.fromCharCode(charCode);
if (str>100)) {
return false;
}
return true;
}
you can use fromCharCode it can return character
please use max length
maxlength="2"
EX.
<!DOCTYPE html>
<html>
<body>
<form action="demo_form.asp">
PIN: <input type="text" name="pin" maxlength="2" size="30"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Try this:
<script type="text/javascript">
function fnc(value, min, max)
{
if(parseInt(value) < 0 || isNaN(value))
return 0;
else if(parseInt(value) > 100)
return "Number is greater than 100";
else return value;
}
</script>
<input type="text" name="textWeight" id="txtWeight" maxlength="5" onkeyup="this.value = fnc(this.value, 0, 100)"/>

Categories

Resources