I am trying to get this Javascript in my application working.
function validateQuantity(field)
{
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for(var i=0; i < field.value.length; ++i)
{
var new_key = value.charAt(i); //cycle through characters
if(((new_key <= "0") || (new_key > "9")) &&
!(new_key == ""))
{
alert("Please enter number and greater than 0 only");
return false;
break;
}
return true;
}
}
And I have a input button as below
<input class="buttonToLink" type="submit" value="Update"
onclick="return validateQuantity(document.getElementById('quantity'))"/>
The above code successfully checks the input of all alphabet such as "abc" or alphabet and numeric such as "abcd123" as false.
However, when I put numeric characters first, along with alphabet such as "123abc", it fails -- it does not show the alert.
What did I do wrong with the code, and how can it be fixed?
function validateQuantity(field) {
if (!/^\d+$/.test(field.value)) { // is an integer
alert("Please enter number and greater than 0 only");
return false;
}
return true;
}
The reason your code doesn't work is because you have the return true statement inside the loop. As soon as it sees a valid integer it will return true and break out of the function, ignoring anything that comes after it. Allowing strings like "123abc" for example.
This is probably what you wanted:
function validateQuantity(field)
{
var value = field.value; //get characters
//check that all characters are digits, ., -, or ""
for(var i=0; i < field.value.length; ++i)
{
var new_key = value.charAt(i); //cycle through characters
if(((new_key <= "0") || (new_key > "9")) &&
!(new_key == ""))
{
alert("Please enter number and greater than 0 only");
return false;
break;
}
}
return true;
}
if (parseInt(new_Key) == new_Key) {
//valid
} else { // it will return NaN
//invalid
}
Try parsing the value as an integer, and compare with the original value.
var isAllNumbers = (parseInt(field.value) == field.value);
Perhaps use a jQuery selector, and use a regex to test for numeric.
var isAllNumbers = $("#quantity").val().match(/\d+$/);
Related
I'm trying to write a function that checks a string for multiple conditions. However, I have reached a wall when trying to figure out how to check if the first character in a string is a letter only.
function SearchingChallenge(str) {
// code goes here
let onlyLetters = /^[a-zA-Z]+$/;
if (str.length > 4 && str.length < 25){
if (onlyLetters.test(str)){
return true;
} else {
return false;
}
} else {
return false;
}
}
"u__adced_123" should return true but it's returning false. I've tried str[0]==onlyLetters but still the same.
onlyLetters.test(str) checks the whole string. To get the first character, use str.charAt(0).
function SearchingChallenge(str) {
let onlyLetters = /^[a-zA-Z]+$/;
if (str.length > 4 && str.length < 25) {
if (onlyLetters.test(str.charAt(0))) {
return true;
} else {
return false;
}
} else {
return false;
}
}
console.log(SearchingChallenge('Hello World!'));
console.log(SearchingChallenge('!dlroW olleH'));
console.log(SearchingChallenge('u__adced_123'));
const SearchingChallenge = str => (
!!str[4] && // > 4
!str[24] && // < 25
(/^[a-z]+$/i).test(str) // alpha
);
// Tests...
// true: greater than four characters
console.log(SearchingChallenge('Fiver'));
// true: less than twenty-five characters
console.log(SearchingChallenge('TwentyFouroooooooooooooo'));
// false: twenty-five or more characters
console.log(SearchingChallenge('TwentyFiveooooooooooooooo'));
// false: contains numbers
console.log(SearchingChallenge('abcd1234'));
// false: less than five characters
console.log(SearchingChallenge('Four'));
I have code where it accepts alphabets, numbers, and spaces but I want to convert it to where it only accepts alphabets (a-z, A-Z) and numbers (0-9) [So basically getting rid of accepting spaces]. Its driving me crazy and I can't figure it out. And please I want to avoid charCode as much as possible!
function check_username() {
//username the user inputted
var text_input = $('#text').val();
if (text_input != "") {
if (text_input.search(/[^a-zA-Z0-9 ]+/) === -1 && text_input[0] != ' ' &&
text_input[text_input.length - 1] != ' ' && text_input.length <= 15) {
alert("Valid");
}
else if (text_input.search(/[^a-zA-Z0-9 ]+/)) {
alert("NOT Valid");
}
}
}
You can use .match and a regular expression /^[0-9a-zA-Z]+$/ Here is a example code:
function alphanumeric(inputtxt) {
var letterNumber = /^[0-9a-zA-Z]+$/;
if (inputtxt.match(letterNumber)) {
console.log('true');
} else {
console.log('false');
}
}
alphanumeric('Test Test5'); //False
alphanumeric('TestTest5'); //True
I am trying to create a javascript function which is called on keypress event on a input which does the following:
Input should be a valid decimal with format (5,2) => (XXXXX.YY) which are variable to the function. Input is restricted if user adds any value which does not conform to the format above.
If existing input starts with . append 0 to the starting automatically
HTML
<input type="text" onkeypress="return checkDecimal(event, this, 5, 2);" id="price2" value="27.15">
Javascript
function checkDecimal(evt, item, lenBeforeDecimal, lenAfterDecimal) {
var charCode = evt.which;
var trimmed = $(item).val().replace(/\b^0+/g, "");
if(checkStartsWith(trimmed, '.') == true){
trimmed = '0' + trimmed;
}
//Allow following keys
//8 = Backspace, 9 = Tab
if(charCode == 8 || charCode == 9){
return true;
}
//Only a single '.' is to be allowed
if(charCode == 46){
var dotOccurrences = (trimmed.match(/\./g) || []).length;
if(dotOccurrences != undefined && dotOccurrences == 1){
return false;
}else{
return true;
}
}
if (charCode > 31 && ((charCode < 48) || (charCode > 57))) {
return false;
}
if ($(item).val() != trimmed){
$(item).val(trimmed);}
//Check the start and end length
if(trimmed.indexOf('.') == -1){
if(trimmed.length >= parseInt(lenBeforeDecimal)){
return false;
}
}else{
var inputArr = trimmed.split(".");
if(inputArr[0].length > parseInt(lenBeforeDecimal) || inputArr[1].length >= parseInt(lenAfterDecimal)){
return false;
}
}
return true;
}
function checkStartsWith(str, prefix){
return str.indexOf(prefix) === 0;
}
Issues
If user inputs 12345.9 and then moves the caret position after 5, user is able to add another digit before the decimal 123456.9 which should not be allowed.
If user inputs 1.9 and then remove 1 and add 5, 5 is added at the end and the entered value becomes 0.95 and not 5.9
JS Fiddle
Consider using a regular expression like:
/^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
that allows everything up to and including your required format, but returns false if the number part is more than 5 digits or if the fraction is more than 2 digits, e.g.:
<input type="text" onkeyup="check(this.value)"><span id="er"></span>
<script>
function check(v) {
var re = /^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
document.getElementById('er').innerHTML = re.test(v);
}
</script>
You'll need separate validation for the final value, e.g.
/^\d{5}\.\d{2}$/.test(value);
to make sure it's the required format.
I don't understand the requirement to add a leading zero to "." since the user must enter 5 leading digits anyway (unless I misunderstand the question).
Ok so im talking in some unput from the user, it must be 4 numbers, and the digits must not be the same. so everything is working accept the part where i check the 4 numbers against each other. i put the string into an array and then compare the array, by
checking the first one against the 2nd, 3rd, 4th,
then i check the second one against the 3rd, and 4th
then i check the third number against the 4th
My issue is the if statement will not work no matter what i try it gets bypassed everytime. I add random returns into the code to see where it goes and it always returns 12 no matter what even if the numbers i enter are 1111 it still passes.
Ive spent hours trying different stuff please help me!!
function validate(guess){
var user_guess = guess;
var valid = true;
var counter = 0;
parseFloat(user_guess);
if(user_guess.length == 4){
if((user_guess == null) || (isNaN(user_guess))){
validation_alert();
}else{
var guess_string = toString(user_guess);
var guess_array = guess_string.split('');
var guess_array2 = guess_array;
for(var i = 0; i < 3; i++){
counter = i + 1;
for(c = counter; c < 4; c++){
if(guess_array[i] == guess_array2[c]){
return 11;
valid = false;
validation_alert();
}
}
}
if(valid == true){
return 12;
}else{
return 13;
validation_alert();
}
}//if null
}else{
validation_alert();
}//if 4 end tag
}// function close
Just to prove to you that JavaScript uses function scope and not block scope (if else for ...) which means every var you declare moves automatically to the top of the current function it's running in.
Also note that when you return something you will exit the current function and not execute anything after that.
If you check against length you can be sure it's going to be a number so use === instead which checks against it's type (number, string, bool) as well.
Your 2 first if statements should be reversed I think. In anycase user_guess == null will never validate as the previous if checks on the length === 4.
Normally when you use return every block scope should return something. I haven't edited this but that's expected in strict javascript.
It seems more logical to start with valid=false and you will only set it to true when you are sure it's true. I'll leave that up to you.
function validate(guess){
var user_guess = parseFloat(guess),
guess_string,
guess_array,
guess_array2,
valid = true,
counter = 0,
i = 0,
c;
if (!user_guess || isNaN(user_guess)){
validation_alert();
} else {
if (guess.length === 4){
guess_string = user_guess.toString();
guess_array = guess_string.split('');
guess_array2 = guess_array;
for (i; i < 3; i++){
counter = i + 1;
c = counter;
for (c; c < 4; c++){
if (guess_array[i] == guess_array2[c]){
valid = false;
validation_alert();
return 11;
}
}
}
if (valid){
return 12;
} else {
validation_alert();
return 13;
}
} else {
validation_alert();
}
}
}
If you just need to check if the string has 4 unique number digits its much easier this way:
function isValid(str){
var unique={};
for(var i=0;i<str.length;i++){//for each character in the string
unique[str[i]]=true;//we add the character as a key in unique object(the =true doesnt really matter)
}
var chars=Object.keys(unique);//we get an array with the keys in the object(we get an array with the unique characters)
if(chars.length != 4) return false; //if the unique chracters are different than 4, its not valid so return false
chars.sort();//we order the array in lexicographical order
if(chars[0]>= '0' && chars[0] <='9' && chars[3]>= '0' && chars[3] <='9') return true;//if the first character and the last ones are digits, then the ones in the middle wil be digits as well because of the sort we made. If they are, return true
return false;//if they are not both digits, return false
}
console.log(isValid('1111'))//false
console.log(isValid('9230'))//true
console.log(isValid('1343'))//false
console.log(isValid('a412'))//false
console.log(isValid(''))//false
I try to check non negative number in jquery.If other then number my function works but for zero and non negative number its doesn't work.Here is my sample fiddle.
Sample Fiddle
Unable to find my mistake.Thanks.
How about DEMO (NOTE: Error messages are OP's own)
$('#txtNumber').keyup(function() {
var val = $(this).val(), error ="";
$('#lblIntegerError').remove();
if (isNaN(val)) error = "Value must be integer value."
else if (parseInt(val,10) != val || val<= 0) error = "Value must be non negative number and greater than zero";
else return true;
$('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>'+error+'</label>');
return false;
});
This should work:
$('#txtNumber').keyup(function() {
var num = $(this).val();
num = new Number(num);
if( !(num > 0) )
$('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be non negative number and greater than zero.</label>');
});
Note: The parseInt() ignores invalid characters if the first character is numeric but the Number() take cares of them also
$('#txtNumber').keyup(function()
{
$('#lblIntegerError').remove();
if (!isNaN(new Number($('#txtNumber').val())))
{
if (parseInt($('#txtNumber').val()) <=0)
{
$('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be non negative number and greater than zero.</label>');
return false;
}
}
else
{
$('#txtNumber').after('<label class="Error" id="lblIntegerError"><br/>Value must be integer value.</label>');
return false;
}
});
if (isNaN($('#txtColumn').val() <= 0))
That's not right..
You need cast the value to an integer since you're checking against an integer
var intVal = parseInt($('#txtColumn').val(), 10); // Or use Number()
if(!isNaN(intVal) || intVal <= 0){
return false;
}