How can I check the length of in String in JavaScript? Here is a small code example:
if(value != null && value != "" && value.length !== 10 && !value.match(/^\d*$/)){
// do something
}
The expression 'value.length !== 10' doesn´t work. A String must contain at least 10 characters. How can I solve this problem?
Instead of match, test can be used with proper regex \d{10,}.
if (value && /^\d{10,}$/.test(value.trim()))
To Get the string length of a value for example:
var value="This is a string";
var string_length=value.length;
/*The string length will result to 16*/
Hope this helps
var regex = new RegExp(/^\d*$/),
value = $.trim("1234567890");
if (value.length >= 10 && regex.exec(value)) {
// correct
} else {
// incorrect
}
Related
I'm using the typeof command to make sure that only 1 of the 2 input fields of this temperature (Celsius to/from Fahrenheit) calculator is populated with data and it has to be a number. If the input is not a valid number or both fields are populated, the app will throw an error message.
The problem: nothing satisfies this condition - the errorMessage is always shown, even if I type in a valid number.
Is typeof the right solution to this problem? If it is, why is this code not working?
document.getElementById('temperature-form').addEventListener('submit', calculateResult);
function calculateResult(e) {
e.preventDefault();
const celsiusInput = document.getElementById('celsius');
const fahrenheitInput = document.getElementById('fahrenheit');
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) {
resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
} else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';
} else {
errorMessage('Please add a number in one of these fields');
}
}
Many thanks!
You could check the value properties of each input to see if they are numbers using the isNaN() function like so:
function calculateResult(e) {
e.preventDefault();
//Get the value of each input box
const celsiusValue = document.getElementById('celsius').value;
const fahrenheitValue = document.getElementById('fahrenheit').value;
//Get the result element
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if(!isNaN(celsiusValue) && (fahrenheitValue === null || fahrenheitValue === "")){
//Only celsiusValue has a valid number
resultOutput.value = (celsiusValue * 1.8 + 32) + ' Fahrenheit';
}else if(!isNaN(fahrenheitValue ) && (celsiusValue === null || celsiusValue === "")){
//Only fahrenheitValue has a valid number
resultOutput.value = ((fahrenheitValue - 32)/1.8) + ' Celsius';
}else if(!isNan(celsiusValue) && !isNan(fahrenheitValue )){
//Both contain a valid number
//Figure this one out as you didn't account for it
}else{
//Neither is a valid number
errorMessage('Please add a number in one of these fields');
}
}
Documentation of isNaN():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
When doing const celsiusInput = document.getElementById('celsius') you're getting the DOM Element, not the value.
In order to obtain de value you'd have to check for the property value.
So you'd end up with something like this:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
Now if we do typeof celsiusValue we'll always get string, because text/number inputs always accept text (check input's type property for more info).
The proper way to check if there are numbers or letters is using Regular Expressions.
I'll leave a simple example to act as a starting point for you:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
if(/\D/.test(celsiusValue)) {
alert("There is something that's not a number in the Celsius input!")
}
First of by doing a comparison like this fahrenheitInput === null you're comparing a DOM element against the value null.
That will only evaluate to true if the DOM Element never existed.
Secondly the typeof method will always evaluate to a String on DOM element types, so again this will always be false.
To really get what you want you have to do a proper check
To check if both input fields are supplied, simply checking the length of the values will surface:
if(fahrenheitInput.length > 0 && celsiusInput.length > 0) //fail
If fahrenheitInput only is given:
if(!isNaN(Number(fahrenheitInput)) //convert
if celsiusInput only is given:
if(!isNaN(Number(celsiusInput)) //convert
Finally if all checks above don't check our, fail
Here is my jsFiddle
Its on the Phone method, no the name one
Now is this line right? I only want it to be true if the first 3 letters are 087
var RightStarting3 = value.substring(0,2) == (087);
if (BlankPass || LessThan10 || RightStarting3 || GreaterThan10 || (HasSpaces > 0))
{
document.getElementById('Phone').style.background = "red";
return false;
}
else {
document.getElementById('Phone').style.background = "white";
document.getElementById("PhoneTick").style.visibility="visible";
return true;
}
var RightStarting3 = value.substring(0,3) === ('087');
value.substring(x) returns a string and 087 and 87 mean the same to javascript interpreter. You should change one of the datatypes so that they match...
Either the substring to an integer:
var RightStarting3 = parseInt(value.substring(0,2)) == 87;
Or the value you're comparing against to a string:
var RightStarting3 = value.substring(0,3) == "087";
Secondly -- you are invoking ValidateName() immediately (in your assignment to NamePass). Is this really necessary? There will be empty values on page load.
I think with the javascript substring(x,y) method, the y value is the value at which to stop the selection. So in your example the first 3 characters will not be selected and instead the first 2 characters will be selected.
var a = "123";
// this returns "12"
alert(a.substring(0,2));
You probably want to use var RightStarting3 = value.substring(0,3) == ('087'); instead.
KingKongFrom's answer is correct, I would add that you should make sure that value (whatever that is) isn't null first, cause if you try to call substring on null it will thrown an exception and die.
My Code:
I tried the following code
<SCRIPT type="text/javascript">
var num = "10";
var expRegex = /^\d+$/;
if(expRegex.test(num))
{
alert('Integer');
}
else
{
alert('Not an Integer');
}
</SCRIPT>
I am getting the result as Integer. Actually I declared the num varibale with double quotes. Obviously it is considered as a string. Actually I need to get the result as Not an Integer. How to change the RegEx so that I can get the expected result.
In this case, it should give the result as Not an Integer. But I am getting as Integer.
if(typeof num === "number" &&
Math.floor(num) === num)
alert('Integer');
else
alert('Not an Integer');
Regular expressions are there to work on strings. So if you tried it with something else than a string the string would either be converted or you would get an error. And yours returns true, because obviously the string only contains digit characters (and that is what you are checking for).
Use the typeof operator instead. But JavaScript doesn't have dedicated types for int and float. So you have to do the integer check yourself. If floor doesn't change the value, then you have an integer.
There is one more caveat. Infinity is a number and calling Math.floor() on it will result in Infinity again, so you get a false positive there. You can change that like this:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(num) === num)
...
Seeing your regex you might want to accept only positive integers:
if(typeof num === "number" &&
isFinite(num) &&
Math.floor(Math.abs(num)) === num)
...
RegExp is for strings. You can check for typeof num == 'number' but you will need to perform multiple checks for floats etc. You can also use a small bitwise operator to check for integers:
function isInt(num) {
num = Math.abs(num); // if you want to allow negative (thx buettner)
return num >>> 0 == num;
}
isInt(10.1) // false
isInt("10") // false
isInt(10) // true
I think it's easier to use isNaN().
if(!isNaN(num))
{
alert('Integer !');
}
else
{
alert('Not an Integer !');
}
Léon
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","") == "")
if I have 10 different strings and I want to find if at least 2 that contain some value... what would the logic be on that?
all "and's" does not work and neither does all "or's"
Below won't work...
This will only work if every one has value...
if(str1 && str2 && str3 && str4 && str5 && str6 && str7 && str8 && str9 && str10)
This will be true if there is only one value... needs to be at least 2
if(str1 || str2 || str3 || str4 || str5 || str6 || str7 || str8 || str8 || str10)
Is there any easy way to do this?
Edit: More info...
There is going to be ten long strings and I need to chunk through them and check (for instance) if any of the first characters are the same, then check if any of the second characters are the same etc. but I can add all the extra "charcode at" stuff in later. The same answer will work for checking full length strings and finding if two are the same.
Put all strings in an array say myArray and count strings having the value and see if count is greater than or equal to 2
var count = 0;
for (var index=0; index<myArray.length; index++) {
if(myArray[index].indexOf(value) != -1) {count++;}
if(count==2) break;
}
if(count==2){alert("atleast 2 have value");}
else {alert("Less than 2 have value");}
Add each string to an array and then iterate the array, incrementing a counter every time a match is found:
var val = "search string here";
var arr = [str1, str2, str3, str4, str5, str6, str7, str8, str9, str10];
var matches = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].indexOf(val) > -1 && ++matches >= 2) break;
}
if (matches >= 2) {
alert("validates");
} else {
alert("failed");
}
It's a little unclear what you're asking. If you want to check if at least two of the strings are duplicates of each other, then the following should do:
function duplicatesExist (array) {
var hash = {};
for ( var i = 0 ; i < array.length ; i++ ) {
if ( hash.hasOwnProperty(array[i]) ) return true;
else hash[array[i]] = true;
}
return false;
}
duplicatesExist([str1, str2, str3, ...]);
Make an array containing the ten strings. Create a "nonEmptyItemCount" variable (or similar) and set it to zero. Loop through the array, testing the current item, and if it has a value increment nonEmptyItemCount. When you are done looping, see if nonEmptyItemCount >= 2
To test the number of strings that are not empty it is easy to build an array of those strings (let's call it arrayOfStrings). The number of not empty strings you can find with
arrayOfStrings.filter(function(s) { return s }).length
I hope this is what you were looking for. To explain it: filter returns all elements of the array where the function returns true. The filter function gets the string as an argument. We just return it and while javascript is coercing the value into a boolean every empty string will evaluate to false. This leaves only the not empty ones in the result. A length of the resulting array is the number you are looking for and you compare it to your wanted minimum