I need a field which can only take numbers, but not allow for signs such as "+", "-", "*" and "/". 0 can also not be the first number. If I make an Input field and set it's type to "number" I'm still allowed to write at least "+" and "-", and I can't quite seem to prevent the user from writing 0 as the first number either.
$('input#update-private-ext').on('keydown', function (e) {
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
});
The above was my first attempt at making the function disallow 0 as the first character, but it doesn't seem to work. It just lets me write 0 as the first character. I also tried this to stop the signs from showing up:
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = String.fromCharCode(e.keyCode);
if ($(this).text.length == 0 && value == 0) {
return false;
}
if (badChars.indexOf(value) == -1) {
return false;
}
});
But with the badChars check, I cannot write anything in my field. So what am I missing here?
You should use e.key to get the current key pressed. String.fromCharCode(e.keyCode) gives the wrong result.
Also you should check if the bad chars is not -1. If it is, then your char is not a bad character and so you should not enter the if.
If you want to get the length of the input field you should use jQuery's .val() and not .text(). Or you can simply do it without jQuery using this.value.length.
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext">
When you compare numbers and strings you must remember that numbers are encoded by using character codes from 48 to 57 and comparing strings with numbers is error-prone in JavaScript as there are many implicit coercions. You should be comparing objects of the same type to avoid the confusion.
In your case, the comparison should be done in the way that parsed string from the String.fromCharCode equals '0' - zero character (string), not the 0 as a number.
There are also issues of the keyCode parsing which yield strange values for the symbols because you would have to manually consider if Shift and other meta keys are pressed when parsing. Save yourself a trouble and just use e.key to get parsed key value.
By the way, please see the difference between this and $(this). Basically, in your case, it means that real instance of the input field is the first element of JQuery iterator - $(this)[0]. You may then just use this, which is automatically set to the target element in the event handler.
Please see the following example of blocking first 0 with debug information printed out:
$('input#update-private-ext').on('keydown', function (e) {
var value = e.key;
console.log('Typed character:');
console.log(value);
console.log('$(this)');
console.log($(this));
console.log('this (input element):');
console.log(this);
console.log("input's value:");
console.log(this.value);
if (this.value.length == 0 && value == '0') {
console.log('blocked');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
In order to block other characters you can just filter them the following way (remember that indexOf returns -1 when the index is not found):
$('input#update-private-ext').on('keydown', function (e) {
var badChars = '+-/*';
var value = e.key;
if (this.value.length == 0 && value == '0') {
return false;
}
//Please note NOT EQUALS TO -1 which means not found.
if (badChars.indexOf(value) !== -1) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="update-private-ext" />
You can do something like this below:
1. Check for bad chars if badChars.indexOf(v) >= 0.
2. Disallow starting from 0 by checking if the input starts from 0 and if yes, set the input field to blank.
This can give you a start!
$('input#update-private-ext').on('keydown', function(e) {
var badChars = '+-/*';
var v = e.key;
if (badChars.indexOf(v) >= 0) {
return false;
}
if ($(this).val().startsWith('0')) {
$(this).val("");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="update-private-ext" />
Related
I'm using the following function to remove non-digit characters from input fields onkeyup (as posted in numerous places). The function works fine for text inputs but when linked to a number input, the number input is completely erased when a non-digit character is typed.
Thoughts?
function RemoveNonNumeric(e)
{
var el = e.target;
el.value = el.value.replace(/\D/g,"");
return;
}//end RemoveNonNumeric
What happens is as soon as there is a non-numeric character in a number input field... the value becomes empty. One way to solve this would be to save the last true numeric value and replace the current value with that if it becomes an empty value. Seems kind of hacky, but see if it works for you:
JSFiddle
var lastNumericValue = 0;
function RemoveNonNumeric(e)
{
if(e.keyCode === 8)
return;
var el = e.target;
if(el.value === "") {
el.value = lastNumericValue;
} else {
lastNumericValue = el.value;
}
}
on second thought... how about preventing the non-numeric values from ever being placed instead of removing them after the fact? Run the following onkeypress
JSFiddle
function RemoveNonNumeric(e) {
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
};
If you debug, you will find that when the value of a number input is invalid, el.value returns an empty string. I am unaware of a workaround.
I have been trying to allow numeric field and one decimal point in my Grid.Its work fine when its suitable for input box.
when i am calling onKeyPress the script work fine for "input box" rather than on "Div element"
In "Div element",when i am supposed to use this .It allow to access only for number rather Alphabet
hence,while coming to "decimal place" its not working as it should.[ It's allowing many Dot's]
<script>
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
<div onKeyPress="return restrictChars(event, this)">
Any Ideas how we could achieve it
For an <input>, it is required to check the value attribute, hence why obj.value is used in your code above. A div element doesn't have a value attribute. You have to check it's innerHTML (mdn docs). If you replace all instances of obj.value with obj.innerHTML, your code should work.
You need to use jQuery keypress() method to handle this right:
$("#d input").keypress(function(event){
return restrictChars(event);
});
See the working fiddle:
http://fiddle.jshell.net/ePvJ8/1/
I was trying to make a javascript function which will check if the user entered value inside a text field cannot be less than 9 digits & it cannot be all 0s.
This is what I made
function CheckField(field)
{
if (field.value.length <9 || field.value=="000000000")
{
alert("fail");
field.focus();
return false;
}
else
{
return true;
}
}
<input type ="text" id="number1" onBlur='return CheckField(this)'>
But this doesnt check the condition where user enters more than 9 values and all 0's. It checks only for 1 condition that is with exact 9 zeros 000000000
So, if I understand that right you want the user to be able to enter a number with more than 9 digits, but they cannot be all zeros, right?
This can be done with a regexp:
var value; // Obtain it somehow
if (/^\d{9,}$/.test(value) && !/^0+$/.test(value)) {
// ok
}
What this checks is whether the value is at lest 9 digits (it does not allow anything but digits) and that they are not all 0s.
This should check for both conditions:
function CheckField(field){
return !/0{9}/.test(field.value) && /\d{9}/.test(field.value);
}
Try something like this:
var valueEntered = field.value;
if (parseInt(valueEntered) == 0) ...
or if you wanted to check if it was a number as well:
if (!(parseInt(valueEntered) > 0))
Two options spring to mind. You can try parsing the value as a number and test for isNaN or != 0
var parsed = parseInt(field.value, 10);
if(field.value.length < 9 || !(isNaN(parsed) || parsed != 0)){
alert("fail");
... rest of code
}
Or you could use a regex
if(field.value.length < 9 || !/[^0]/.test(field.value){
alert("fail");
... rest of code
}
The first option is probably quicker.
try this:
if (field.value.length <9 || field.value.replace("0","") == "")
I have to check whether a form field contains '#' at start of user input & is it contains it at all. It works fine for checking if its at start of the string. But when I add checking whether input contains '#' at all or not. It fails. Here is my code
function email_valid(field)
{
var apos=field.update.value;
apos=apos.indexOf('#');
if (apos>0 ||((apos.contains('#')== 'FALSE')))
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
EDIT
This function in this form is checking both if # is at 1st place & 2ndly is it in the input at all or not.
function #_valid(field)
{
var ref=field.update.value;// I needed ref 4 other things
var apos=ref.indexOf('#');
if (apos>=0 )
{
if (apos==0)
{
return true;
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
}
}
else { field.t_update3.value="";
alert('plz enter a valid refernce');
return false;
} }
Consider:
var apos = value.indexOf('#');
if (apos >= 0) {
// was found in string, somewhere
if (apos == 0) {
// was at start
} else {
// was elsewhere
}
} else {
// not in string
}
and
var apos = value.indexOf('#');
if (apos == 0) {
// was at start
} else if (apos > 0) {
// was elsewhere
} else {
// not in string
}
Why not just
if (apos !== 0) { /* error; */ }
The "apos" value will be the numeric value zero when your input is (as I understand it) valid, and either -1 or greater than 0 when invalid.
This seems like a strange thing to make a user of your site do, but whatever. (If it's not there at all, and it must be there to be valid, why can't you just add the "#" for the user?)
You can just check to make sure that apos is greater than -1. Javascript's indexOf() will return the current index of the character you're looking for and -1 if it's not in the string.
edit Misread a bit. Also make sure that it's not equal to 0, so that it's not at the beginning of the string.
function email_valid(field)
{
var fieldValue =field.update.value;
var apos = apos.indexOf('#');
if (apos > 0 || apos < 0)//could also use apos !== 0
{ alert('plz enter valid input');
return false;
}
else
{ return true; }
}
apos is the value returned by indexOf, it will be -1 if there is no # in the user input. It will be 0 if it is the first character. It will be greater than 0 if the user input contains an # . JavaScript has no contains method on a String.
Try:
function email_valid(field) {
//var apos=field.update.value;
var apos = field;
//apos=apos.indexOf('#');
apos = apos.indexOf('#');
if( (apos < 0) ) {
//alert('plz enter valid input');
alert('false');
} else {
alert('true');
}
}
email_valid('blah');
Checks for # anywhere. Or, if you want to check for # just at the beginning, change if( (apos < 0) ) { to if( (apos == 0) ) {. Or, if you want to make sure it's not at the beginning, then if( (apos > 0) ) {.
apos will be -1 if the string was not found. So your code should be as follows:
function email_valid(field)
{
var apos=field.value;
apos=apos.indexOf('#');
if (apos<=0) // handles '#' at the beginning and not in string at all.
{
alert('plz enter valid input');
return false;
}
else
{ return true; }
}
I also changed your initial assignment to remove the .update portion as that would cause it to fail when field is a reference to an input.
In the second if condition, apos is a number, not a string.
You're trying to write
if (field.update.value.charAt(0) == '#' && field.update.value.indexOf('#', 1) < 0)
Learn about Regular expressions if you haven't already. Then lookup Javascript's String#match. There is no need to find wether the input starts with an "#" as if it contains an "#" that will also return true if the "#" is at the start of the string.
Also, for free, return true and return false are generally bad style. Just return the thing you passed to if (that evaluates to a boolean).
All in all:
function validate_input(str) {
return str.match(/#/);
}
I reccomend passing the function a string (field.value or some-such) rather than the field itself as it makes it more generic.
Update: revised answer based on comments. code below will only return true if the value contains an "#" symbol at the first character.
If this is a JavaScript question, then this should be fine.
function email_valid(field){
var apos=field.update.value;
if(apos.indexOf('#') != 0){
alert('plz enter valid input');
return false;
} else {
//field contains an '#' at the first position (index zero)
return true;
}
}
That said, your parameter "field" if it actually refers to an input field element, should only require this code to get the value (e.g. I'm not sure where the ".update" bit comes into play)
var apos = field.value;
I would also rename this function if it isn't doing "email validation" to something a little more appropriately named.
I have a text field that allows a user to enter their age. I am trying to do some client-side validation on this field with JavaScript. I have server-side validation already in place. However, I cannot seem to verify that the user enters an actual integer. I am currently trying the following code:
function IsValidAge(value) {
if (value.length == 0) {
return false;
}
var intValue = parseInt(value);
if (intValue == Number.NaN) {
return false;
}
if (intValue <= 0)
{
return false;
}
return true;
}
The odd thing is, I have entered individual characters into the textbox like "b" and this method returns true. How do I ensure that the user is only entering an integer?
Thank you
var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
alert('I am an int');
...
}
That will absolutely, positively fail if the user enters anything other than an nonnegative integer.
For real int checking, use this:
function isInt(value) {
return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10));
}
The problem with many int checks is that they return 'false' for 1.0, which is a valid integer. This method checks to make sure that the value of float and int parsing are equal, so for #.00 it will return true.
UPDATE:
Two issues have been discussed in the comments I'll add to the answer for future readers:
First, when parsing string values that use a comma to indicate the decimal place, this method doesn't work. (Not surprising, how could it? Given "1,001" for example in the US it's an integer while in Germany it isn't.)
Second, the behavior of parseFloat and parseInt has changed in certain browsers since this answer was written and vary by browser. ParseInt is more aggressive and will discard letters appearing in a string. This is great for getting a number but not so good for validation.
My recommendation and practice to use a library like Globalize.js to parse numeric values for/from the UI rather than the browser implementation and to use the native calls only for known "programmatically" provided values, such as a string parsed from an XML document.
use isNaN(n)
i.e.
if(isNaN(intValue))
in place of
if (intValue == Number.NaN)
UPDATE
I have fixed the code that had an error and added a var called key to store the key pressed code using keyCode and which, that depend of the browser.
var key = e.which || e.keyCode;
Thanks Donald.McLean :)
If you want to check if you are writing numbers while typing (and avoid writing other characters into your input field), you can use this simple function and you can define the elements allowed (this include whatever you want to filter). In this way you can choose not only integers but for example a certain group of characters. The example is based in jQuery to attach it to an input field.
$('#myInputField').keypress(function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval of values (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
If you use other key than the defined, it won't appear into the field. And because Angular.js is getting strong these days. this is the directive you can create to do this in any field in your web app:
myApp.directive('integer', function()
{
return function (scope, element, attrs)
{
element.bind('keydown', function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
}
});
But what happens if you want to use ng-repeat and you need to apply this directive only in a certain number of fields. Well, you can transform the upper directive into one prepared to admit a true or false value in order to be able to decide which field will be affected by it.
myApp.directive('rsInteger', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
if (attrs.rsInteger === 'true') {
element.bind('keydown', function(e)
{
var key = e.which || e.keyCode;
if (!(key >= 48 && key <= 57) && // Interval (0-9)
(key !== 8) && // Backspace
(key !== 9) && // Horizontal tab
(key !== 37) && // Percentage
(key !== 39) && // Single quotes (')
(key !== 46)) // Dot
{
e.preventDefault();
return false;
}
});
}
}
}
});
To use this new directive you just need to do it in a input type text like this, for example:
<input type="text" rs-integer="true">
Hope it helps you.
I did this to check for number and integer value
if(isNaN(field_value * 1) || (field_value % 1) != 0 ) not integer;
else integer;
Modular Divison
Example
1. 25.5 % 1 != 0 and ,
2. 25 % 1 == 0
And
if(field_value * 1) NaN if string eg: 25,34 or abcd etc ...
else integer or number
function isInt(x) {return Math.floor(x) === x;}
If your number is in the 32bit integer range, you could go with something like:
function isInt(x) { return ""+(x|0)==""+x; }
The bitwise or operator forces conversion to signed 32bit int.
The string conversion on both sides ensures that true/false want be matched.
Nobody tried this simple thing?
function isInt(value) {
return value == parseInt(value, 10);
}
What's wrong with that?
You may use isInteger() method of Number object
if ( (new Number(x)).isInteger() ) {
// handle integer
}
This method works properly if x is undefined or null. But it has poor browser support for now
I found the NaN responses lacking because they don't pick up on trailing characters (so "123abc" is considered a valid number) so I tried converting the string to an integer and back to a string, and ensuring it matched the original after conversion:
if ("" + parseInt(stringVal, 10) == stringVal) { alert("is valid number"); }
This worked for me, up until the numbers were so large they started appearing as scientific notation during the conversion.
...so of course this means you could enter a number in scientific notation, but checking minimum and maximum values as well would prevent that if you so desire.
It will of course fail if you use separators (like "1,000" or "1.000" depending on your locale) - digits only allowed here.
If (enteredAge < "1" || enteredAge > "130") ......
Simple and it works....until they develop immortality