Is there a good IP Mask plugin for JQuery? I've tried Masked Input Plugin but it doesn't IP Addresses with less than 12 digits. Then I've tried meioMask and this doesn't work with less than 12 digits either. Any suggestions?
You can find your answer in this post :
http://mlntn.com/2009/12/30/jquery-ip-address-plugin/
and a demo for you to try
http://mlntn.com/demos/jquery-ipaddress/
This is an older post however for someone who wants an easy way to manipulate multiple inputs, without using a bulking plugin, or having to worry about documentation or methods, here's a simple class selector method that does it all for you. Its IPv4 only but it sounds like your needs are pretty simple.
//jQuery 1.9+ selector pattern,
//To get working with an older version
//Swap first line to $(".ip").bind('keydown',function(e){
//To get working with jQuery versions support .live
//$(".ip").live('keydown',function(e){
$(document).on('keydown',".ip",function(e){
var code = e.keyCode || e.which;
var sections = $(this).val().split('.');
//Only check last section!
var isInt = ((code >= 48 && code <= 57) || (code >= 96 && code <= 105));
var hasSlash = $(this).val().indexOf("/") == -1;
if(isInt){
if(hasSlash){
if(sections.length < 4){
//We can add another octet
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
$(this).val($(this).val()+"."+String.fromCharCode(code));
return false;
}
return true;
} else {
//Lets prevent string manipulations, our string is long enough
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
return false;
}
return true;
}
} else {
var cidr_split = $(this).val().split('/');
var target_val = parseInt(cidr_split[1]+String.fromCharCode(code));
return (target_val < 33 && target_val.toString().length < 3 && parseInt(cidr_split[1]) != 0);
}
} else if(code == 191){
//CIDR Slash
return ($(this).val().indexOf("/") == -1);
} else if(code == 8 || code == 46 || code == 9 || code == 13){
return true;
}
return false
});
To break this down for understanding, you bind the class "ip" in your input, it will handle the rest automatically :D This version supports CIDR notation (eg: 192.168.1.1/16) it only allows valid addresses to be input, to remove CIDR function you can use use the following snippet (not tested)
//jQuery 1.9+ selector pattern,
//To get working with an older version
//Swap first line to $(".ip").bind('keydown',function(e){
//To get working with jQuery versions support .live
//$(".ip").live('keydown',function(e){
$(document).on('keydown',".ip",function(e){
var code = e.keyCode || e.which;
var sections = $(this).val().split('.');
//Only check last section!
var isInt = ((code >= 48 && code <= 57) || (code >= 96 && code <= 105));
if(isInt){
if(sections.length < 4){
//We can add another octet
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
$(this).val($(this).val()+"."+String.fromCharCode(code));
return false;
}
return true;
} else {
//Lets prevent string manipulations, our string is long enough
var val = parseInt(sections[sections.length-1]+String.fromCharCode(code));
if(val > 255 || parseInt(sections[sections.length-1]) == 0){
return false;
}
return true;
}
} else if(code == 8 || code == 46 || code == 9 || code == 13){
return true;
}
return false
});
I am providing the code here for two purposes 1) This is something i believe needs to be addressed, 2) i hope to contribute to the world
The snippet is not designed to be pulled apart, nor support IPv6, if you need IPv6 Support please see https://code.google.com/p/jquery-input-ip-address-control/ that anyulled suggested.
But aside from the complex syntax, it breaks the octets apart, and only checks the "active" octet, it supports any VALID address (0.0.0.0, 0.0.0.0/0, ect) so use wisely it does not do any fancy checking other than preventing invalid input. If you're looking for a checker, please see Santiago Elvira Ramirez's post about the IP Address validator.
You could try using this plugin https://code.google.com/p/jquery-input-ip-address-control/
The working examples from the Masked Input Plugin -
http://digitalbush.com/projects/masked-input-plugin/
Are less than 12 characters:
jQuery(function($){
$("#date").mask("99/99/9999");
$("#phone").mask("(999) 999-9999");
$("#tin").mask("99-9999999");
$("#ssn").mask("999-99-9999");
});
They have working examples which are running perfectly?
What is exatly is your issue and can you post anymore in depth information?
jQuery(function($){
$("#MyElementID").mask("10.0.0.0"); //Does this not work?
});
Are you trying to counter for 1-3 digits in each field?
eg to be able to.
$("#MyElementID").mask("1.0.0.0"); //this
$("#MyElementID").mask("10.10.10.10"); //or this
$("#MyElementID").mask("100.100.100.100"); //or this
If you be more descriptive you can get help..
If you are after that you can try something simpler by watermarking the input box rather than enforcing a mask, so you can vary the numbers that can be entered.
See Jquery-Watermark - http://code.google.com/p/jquery-watermark/
i found this and you donĀ“t need to install plugins
function fnValidateIPAddress(ipaddr) {
//Remember, this function will validate only Class C IP.
//change to other IP Classes as you need
ipaddr = ipaddr.replace( /\s/g, "") //remove spaces for checking
var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; //regex. check for digits and in
//all 4 quadrants of the IP
if (re.test(ipaddr)) {
//split into units with dots "."
var parts = ipaddr.split(".");
//if the first unit/quadrant of the IP is zero
if (parseInt(parseFloat(parts[0])) == 0) {
return false;
}
//if the fourth unit/quadrant of the IP is zero
if (parseInt(parseFloat(parts[3])) == 0) {
return false;
}
//if any part is greater than 255
for (var i=0; i<parts.length; i++) {
if (parseInt(parseFloat(parts[i])) > 255){
return false;
}
}
return true;
} else {
return false;
}
}
Related
Regular Expression: /^[1-9][0-9]*$/
The regexp works as intended on http://www.phpliveregex.com
My problem is that it doesn't work when implemented with JS, see my code on http://jsfiddle.net/LHHU7
The JS:
$("#mytextbox").on("keypress", function(event) {
var re = /^[1-9][0-9]*$/;
var key = doKey(arguments[0] || window.event);
var char = String.fromCharCode(key);
if (key == 8 || key == 37 || key == 39 || re.test(char)) {
return true;
}
return false;
});
$('#mytextbox').on("paste",function(e)
{
e.preventDefault();
});
function doKey(event) {
var key = event.keyCode | event.charCode;
return key;
}
Test cases expected:
0001 fail
11 11 fail
1000 success
1264 success
5001 success
What's happening with my code:
0001 fail WORKING
11 11 fail WORKING
1000 success NOT WORKING
1264 success WORKING
5001 success NOT WORKING
For some reason 0 won't be entered. I've already tried on chrome, with no success. I've tried changing my RegExp multiple times with no different results. I've also tried different implementations on my code, but still no success.
Please see if you can get it working on my jsfiddle before posting your answers. Thanks!
You're only checking a single character (the latest one) against the regex, when you probably really want to match the content of the textbox + the character. This makes it impossible to enter a zero at all, since it will always be matched against ^[1-9].
Matching the existing textbox value + the character should work better;
if (key == 8 || key == 37 || key == 39 ||
re.test(document.getElementById("mytextbox").value + char)) {
return true;
}
As #Joachim Isaksson mentioned, you are only looking at the last character so your regex is wrong. Update regex to:
var re = /^[0-9]$/;
This will match one number, 0-9.
Edit the Following to your code it works fine DEMO
var testString=$('#mytextbox').val();
if (key == 8 || key == 37 || key == 39 || re.test(testString + char) )
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 tried to make a javascript function to validate integer values from a text box. What is the best way to validate it so that only integer and float values are acceptable?
Required java script function for number validation.
// remove whitespaces
var input = input.replace(/\s+/g,"");
// check if the input is a valid number
if(isFinite(input) && input != ''){
// do your thing
}
Remember that isFinite only accepts values like '20.50' and not '20,50' as is custom in some countries. If you need this kind of flexibility you need to do additional string preprocessing. And with this solution only spaces are allowed as thousand delimiters (e.g '100 000').
Unfortunately the check for an empty string is necessary since isFinite('') returns true.
You could also use this function from user CMS (for a detailed explanation see: Validate decimal numbers in JavaScript - IsNumeric())
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Best ever solution for me for numeric validation in javascript.
function isFloat(evt) {
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
alert('Please enter only no or float value');
return false;
}
else {
//if dot sign entered more than once then don't allow to enter dot sign again. 46 is the code for dot sign
var parts = evt.srcElement.value.split('.');
if (parts.length > 1 && charCode == 46)
{
return false;
}
return true;
}
}
Just Copy and past javascript code and apply to your textbox onkeypress like this ..
<input type="text" onkeypress="return isFloat(event)" />
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();
}
}
<input class="number-only" type=text />
JavaScript has a built in function, isNaN(text). Just pass the text of your text box to this function to get a Boolean result.
var valid = !isNaN(value);
Eg:
!isNaN('0'); // true
!isNaN('34.56'); // true
!isNaN('.34'); // true
!isNaN('-34'); // true
!isNaN('foo'); // false
!isNaN('08'); // true
!isNaN(''), !isNaN(' '), !isNaN('\n\t'), etc are all true!
Whitespace test + isNaN FTW:
var valid = !/^\s*$/.test(value) && !isNaN(value);
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 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