HTML textfield whose values cannot be 0 using Javascript - javascript

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","") == "")

Related

Preventing the user from typing certain characters?

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" />

Validating a phone number in javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to be able to accept any way that a user inputs their phone number. I need help to include regular expressions that can validate the length of a number, bracket, hyphens and take care of spaces.
<script>
function Myfuc() {
var x = document.forms[0]["mobile"].value;
var z = document.forms[0]["mobile1"].value;
if(x == null || x == '')
{
alert("Field canot be empty");
return false;
}
if(x[0]!=0) // Starting with zero
{
alert("Mobile number should start with Zero");
return false;
}
var y=isNaN(x); // Checking numerals in first text box
if(y == true)
{
alert("Integers only accepted");
return false;
}
var z1=isNaN(z); // Checking numerals in first text box
if(z1 == true)
{
alert("Integers only accepted");
return false;
}
}
</script>
<form onsubmit="Myfuc()">
Mobile : <input type="text" id="mobile" name="mobile" style="width:40px;" maxlength=3> -
<input type="text" name="mobile1" maxlength=7>
<input type="submit" value="Click" name="sub" >
</form>
Everything you asked is here!!!, Spent 1 hr for this and imma beginner, dont worry code works well :-)
You could use this reg expression. I'm not too good with reg expressions but this could work in your case.
0\d{2}-\d{7}
/* start match with 0
check for 2 additional digits
check for hyphen
check for 7 additional digits after hyphen
*/
I also suck at creating regex expressions; however, you can always do something like this:
var str = document.getElementById('myInput').value,
numberOnly = str.replace(/-/g, ''),
errors = [], i;
if (isNaN(numberOnly)) {
errors.push('You must use numbers!');
} else if (str.split('-')[0].length !== 3 || str.split('-')[1] !== 7 || numberOnly > 10) {
errors.push('Invalid Format!');
} else {
console.log(numberOnly + ' is ok!');
}
if (errors) {
for (i = 0; i < errors.length; i++) {
console.log(i + '. ' + errors[i]);
}
}
It's simply testing each part of the string that is submitted.
First it checks to see (after we remove the hyphen) that the submitted value is actually a number.
Second, it splits the string in half to check if the start of the string has 3 characters, and then if the end of the string has 7 characters; lastly, it tests to see if the number is too large... etc, you can even check if its too small.
If you ever figure out a decent regex, you could instead use a switch statement to catch the errors (if any).
I think one might look like, [0-9]{3}(-)[0-9]{7} or something like that lol.
-
I've been working with PHP for awhile, so I forget if "length" returns a count, or the actual byte-size of a character, e.g. "é" is 2 bytes.
EDIT:
To check if the first character of the string is "0", you can always do:
if (str.length > 0 && str.charAt(0) != 0) { console.log('error'); }

If String starts with a number check the length of the string

i want to use javascript in a .pdf file.
I want to check if a string starts with "1" or with a letter.
If the string starts with "1" i want to check the length of the string.
If the string is 18 chars long, then i want to call my own created function.
If the String is shorter than 18 chars i want to display a message.
If the string starts with a letter, i want to check the length of the string.
If the string is 11 chars long, then i want to call my own created function.
If the String is shorter than 11 chars i want to display a message.
But how i can do this?
var string = "Your String";
if(string[0] === '1'){
if(string.length >= 18 )
callYourFunction();
else
alert("Your Message");
}
else if(isNaN(string[0])){
if(string.length >= 11 )
callYourFunction();
else
alert("Your Message");
}
Here, string.length returns the length of the string as integer.
isNaN() checks whether the parameter is not a number. It returns false if the parameter is a number.
You can use something similar to this:
if (typeof variableName == 'string' || variableName instanceof String){
if(variableName[0] == '1'){
if(variableName.length == 18){
//call your method
console.log("It's 18th character long");
} else if(variableName.length == 11){
//call another method
console.log("It's 11th character long");
}
}
}
You can select the first character like so - string[0].
Strings behave like arrays in this way.
You can test the length of a string like so - string.length
var string1 = "1dgfe";
if (string1[0] == 1 && string1.length > 18){
yourfunction();
} else if (string1[0] == 1 && string1.length < 18){
console.log('your message');
}

Text Box Integer Validation

I need to create a code in HTML/Javascript that will allow a user to enter an answer to a maths question and then the site needs to validate whether that answer is correct.
Been playing around for a few hours and researched the web but not found anything close.
Any help is appreciated!!
You could use javascript for validation,
Look at this example.
var value = Number(intfield.value);
if (Math.floor(value) == value) {
// value is an integer, do something based on that
} else {
// value is not an integer, show some validation error
}
checking if value of a textfield is integer in javascript
Javascript validation
function isInteger(number) {
var getVal = parseInt(number);
if (number.length == 0 || getVal == Number.NaN || getVal <= 0) {
return false;
}
return true;
}

I need a JQuery IP Mask plugin

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;
}
}

Categories