How to tell if not number or letter - javascript

I have the following bit of code which is working, my question is if the user enters something that is not a letter or number how would I go about doing this ?
E.g they enter the letter "?" I want the console to now say " ? is not a letter or number" please see my below code to see what I currently have.
let upperLower = prompt("please enter either a uppercase letter, lowercase letter or a number");
if (!isNaN(parseInt(upperLower))){
console.log(upperLower + " is a number");
}
else if (upperLower == upperLower.toLowerCase()) {
console.log(upperLower + " character is lowercase");
}
else if (upperLower == upperLower.toUpperCase()) {
console.log(upperLower + " character is uppercase");
}`

function isNotAlphanumeric(str) {
return !(str.length === 1 && (/[a-z\d]/i).test(str));
}

using How to check if character is a letter in Javascript?
Implementation:
let upperLower = prompt("please enter either a uppercase letter, lowercase letter or a number");
if( (upperLower.toUpperCase() == upperLower.toLowerCase() || upperLower.codePointAt(0) > 127) && isNaN(parseInt(upperLower))) {
console.log(upperLower + " is not a letter or number");
}
else if (!isNaN(parseInt(upperLower))){
console.log(upperLower + " is a number");
}
else if (upperLower == upperLower.toLowerCase()) {
console.log(upperLower + " character is lowercase");
}
else if (upperLower == upperLower.toUpperCase()) {
console.log(upperLower + " character is uppercase");
}

This problem can be solved using a regular expression. Tested on Regex101.
var foo = prompt("please enter either a character or integer");
// if word character or digit => true, else => false
const bar = new RegExp(/[\da-z]+/, "i");
// is any digit => true, else => false
const numberRE = /\d+/;
if (bar.test(foo)){
// if a number, log it's a number, else it's a string
if (numberRE.test(foo)) {
console.log("You entered a number");
} else {
console.log("You entered a letter");
}
// if input isn't a digit or word character, log this
} else {
console.log("Enter a character or integer!");
}

Use RegEx:
if (/^[0-9]+(?:\.[0-9]+)?$/.test(upperLower)) { // 123 or 123.456
console.log(upperLower, "is a number")
}
if (/^[0-9]+$/.test(upperLower)) { // only 123
console.log(upperLower, "is a number")
}
if (/^[a-z]+$/.test(upperLower)) {
console.log(upperLower, "is a lowercase")
}
if (/^[A-Z]+$/.test(upperLower)) {
console.log(upperLower, "is a uppercase")
}
You can test any regex in regex101.

Related

.includes() Is always returning true

I am trying to make a Wordle type game, I have started on the basics where it is just using the console to tell me weather the letters are correct or not. In the function check letter the first if statement works flawlessly but on the second one when it is checking weather or not the guess and the word both have the same letter just not in the correct spot. But even when the letter is not even in both of the variable it will console "wrong spot" instead of "wrong letter".
const word = "Lucas";
let guessed = prompt("Please Guess The Word");
checkLength()
function checkLength() {
if (word.length == guessed.length) {
console.log("It Worked")
checkLetter(0)
checkLetter(1)
checkLetter(2)
checkLetter(3)
checkLetter(4)
} else {
console.log("It Failed")
guessed = prompt("Please Use 5 Letters");
}
}
function checkLetter(letterPos) {
if (word.charAt(letterPos) == guessed.charAt(letterPos)) {
console.log("Same Letter! " + letterPos)
} else {
let letterW = word.charAt(letterPos)
let letterG = guessed.charAt(letterPos)
if (word.includes(letterW) == guessed.includes(letterG)) {
console.log("Wrong Spot " + letterPos)
} else {
console.log("Wrong Letter " + letterPos)
}
}
}
The problem is that includes returns true or false, not the index, so when both world and guessed don't include the letter, false == false would return true:
if (letterG !== letterw && word.includes(letterW))
The above condition should work.
First, we should clean up the variables. Then, all that needs fixing is the second if statement. We want to check if letterG exists in word, if not, then it's the wrong letter.
function checkLetter(letterPos) {
let letterW = word.charAt(letterPos);
let letterG = guessed.charAt(letterPos);
if (letterW == letterG) {
console.log("Same Letter! " + letterPos)
} else if (word.includes(letterG)) {
console.log("Wrong Spot " + letterPos)
} else {
console.log("Wrong Letter " + letterPos)
}
}

how to tell javascript that the user enter a string in the prompt box and work with it in if statment

how to tell javascript that the user enter a string in the prompt box and work with it in an if statment ? If the user enters a string of letters I want it to alert "You did not enter a number", and if they entered a string if digits then continue with the logic.
var userGess = prompt("guess a number");
var secretNumber = 7;
if (Number(userGess) > secretNumber) {
alert("the number is to high")
} else if (Number(userGess) < secretNumber) {
alert("the number is to low")
} else if (Number(userGess) == secretNumber) {
alert("you are correct")
} else if (userGess == toString(userGess)) {
alert("you didnt type a number")
}
You can use isNaN(userGess) to check if a given string userGess is non-numeric.
However, that returns false if userGess is empty string, so you have to explicitly check it. So your final condition becomes
userGess === "" || isNaN(userGess)
var userGess = prompt("guess a number");
var secretNumber = 7;
if(userGess === "" || isNaN(userGess)) {
alert("You didn't enter a number")
} else if (Number(userGess) > secretNumber) {
alert("the number is to high")
} else if (Number(userGess) < secretNumber) {
alert("the number is to low")
} else if (Number(userGess) == secretNumber) {
alert("you are correct")
}

Password with regular password

I have to do the password by this condition for creating password to follow this characteristics :
Contain at least 12 alphanumeric characters.
Contain both upper and lower case letters.
Contain at least one number (for example, 0-9).
Contain at least one special character (for example,!$%^&*()_+|~-=`{}[]:";'<>?,/).
i did this :
<input type="password" required pattern="^(?=.*[a-zA-Z])(?=.*\d)(?=.*
[!##$%^&*()_+])[A-Za-z\d][A-Za-z\d!##$%^&*{}()_=+]{12,}$"
name="password"
nblur="this.setCustomValidity(this.validity.patternMismatch
? 'Password must contain at least 12 characters, including upper
lowercase numbers and least special character' : '');
if(this.checkValidity()) form.password1.pattern = this.value;">
but when i try to put a password and confirm it always return not valid password
Sorry for this question, but with regExpression i put for this characteritics. Thanks in advance.
Write a series of test in JavaScript and control the submit event for your form.
var testPassword = (function() {
var allTests = [];
var minimumAlphaNumericCharacters = 12;
function countAlphanumeric(password) {
var count = password.length - password.replace(/[a-z]|\d/ig, '').length;
if (count < minimumAlphaNumericCharacters) {
return "Too few Alphanumeric Characters! At least " + minimumAlphaNumericCharacters + " nedded, " + count + " found";
}
return true;
}
allTests.push(countAlphanumeric);
function containsUpperAndLowerCharacters(password) {
var test = (password === password.toLowerCase());
if (test) {
return "Must contain both upper and lower case characters";
}
return true;
}
allTests.push(containsUpperAndLowerCharacters);
var minimumDigits = 1;
function containsMinimumDigits(password) {
var test = password.replace(/\D/ig, '').length;
if (test < minimumDigits) {
return "Must contain at least " + minimumDigits + " digits, " + test + " digits found";
}
return true;
}
allTests.push(containsMinimumDigits);
var minimumSpecials = 1;
function containsMinimumSpecials(password) {
var test = password.replace(/\w/ig, '').length;
if (test < minimumSpecials) {
return "Must contain at least " + minimumSpecials + " special symbols, " + test + " special symbols found";
}
return true;
}
allTests.push(containsMinimumSpecials);
return function testPassword(password) {
return allTests
.map(function(test) {
return test(password);
})
.filter(function(test) {
return test !== true;
});
};
})();
//TEST
var form = document.body.appendChild(document.createElement("form"));
var input = form.appendChild(document.createElement("input"));
var output = document.body.appendChild(document.createElement("pre"));
input.onchange = input.onkeyup = form.onsubmit = function(evt) {
var password = input.value.toString();
var test = testPassword(password);
output.textContent = test.join("\n");
if (evt.type == "submit") {
alert((test.length < 1 ? "Good" : "Bad") + " Password");
}
return false;
};

dynamically change error div based on user input

I want to change my error message depending on how many digits the user enters in credit card field. I'm trying to generate the message variable with this:
let numberDigit;
let creditCardMessage;
if ($cardNumber.val().length < 13) {
numberDigit = 'Too few digits. ';
} else if ($cardNumber.val().length > 16) {
numberDigit = 'Too many digits. ';
}
creditCardMessage = numberDigit + 'Please enter between 13 and 16';
Then I want to pass the creditCardMessage variable in the following function:
function creditCardNumberEvent () {
if (!isCreditCardValid()) {
showErrorMessage ($cardNumber, creditCardMessage, $cardNumber, 'creditCardError');
} else {
removeErrorMessage($cardNumber, '#creditCardError');
}
}
All I get is the first value - the "too few digits." Thanks in advance.
When running your script, you can call CardNumberValid() which returns a Boolean, meaning you can use it in an if statement, like if(CardNumberValid())
function CardNumberValid() {
var valid = true;
var CardNumber = $("#CardNumber");
if (CardNumber.val().length < 13) {
$("#ErrorMsg").text("Too few digits. Please enter between 13 and 16");
valid = false;
} else if (CardNumber.val().length > 16) {
$("#ErrorMsg").text("Too many digits. Please enter between 13 and 16");
valid = false;
}
if(valid){
$("#ErrorMsg").text("");
}
return valid;
}
$('#Validate').click(function() {
alert("The card number " + (CardNumberValid() ? "is" : "is not") + " valid.");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="CardNumber" />
<div id="ErrorMsg" style="color:red;"></div>
<button id="Validate" type="button">Validate</button>
I think this is what you're trying to achieve:
function logValidationMessage() {
var cardNumber = document.getElementById('cardNumber');
var numberDigits = null;
if (cardNumber.value.length < 13) {
numberDigits = 'Too few digits. ';
} else if (cardNumber.value.length > 16) {
numberDigits = 'Too many digits. ';
} else {
numberDigits = 'Card number is valid.';
}
console.log(numberDigits);
}
document.getElementById('btnCheckCardNumber').addEventListener('click', logValidationMessage);
<input type="text" id="cardNumber" />
<input type="button" id="btnCheckCardNumber" value="Check" />
I did figure this out. I created a function as suggested and passed that function as an argument in another function: (which I now know is a callback function)
function creditCardMessageFunction () {
let numberDigit;
let creditCardMessage;
if ($cardNumber.val().length < 13) {
numberDigit = 'Too few digits. ';
} else if ($cardNumber.val().length > 16) {
numberDigit = 'Too many digits. ';
} else {
numberDigit = 'Numeric Values Only. ';
}
creditCardMessage = numberDigit + 'Please enter numbers between 13 and 16.';
return creditCardMessage;
}

How to validate textfield with 0 to 59, it will allow 1,2,3,*/59

I need to validate Textbox for this test cases.
It will allow 0 to 59 no characters and special character not allowed except *,/
It will allow 1,2,3,4 but 1,2,3,60 should not allow
It will allow /59 or 1,2,3,4,/59 but 1,2,3,5,*/59/19 should not allow
i tried,
var input = document.getElementById('configMinute').value;
//console.info("Else Called");
var slashPattern = "/";
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var getStringCheck = checkSpecialChar(input,specialChars);
if(getStringCheck==true){
// string = 1,2,3,*/10
// ,*/
var getStringValues = input.split(',');
var notAllowedCharPattern = "<>#!#$%^&()_+[]{}?:;|'\"\\.~`-=";
var allowedChar = checkSpecialChar(input,notAllowedCharPattern);
if(allowedChar==false){
console.info(getStringValues);
getStringValues.forEach(function(element){
//string = 1 2 3 */10
var validateSlash = checkSpecialChar(element,slashPattern);
if(element.startsWith("*")==true){
var newInput = element.split('/');
console.info("newInput: "+ element);
newInput.forEach(function(element) {
console.info("newInput Foreach: "+ element);
if(element=='*' || (element>=0 && element <=59)){
return true;
}
else{
alert("Please enter numbers between 0 to 59 or '*' ==>1");
document.getElementById('configMinute').focus();
return false;
}
});
}else{
console.info("* Else: "+ element);
if(element=='*' || (element>=0 && element <=59)){
return true;
}else{
alert("Please enter numbers between 0 to 59 or '*' ==>1");
document.getElementById('configMinute').focus();
return false;
}
}
});
}else{
alert ("File name has special characters \nAllowed Characters are *,/ ==>3");
document.getElementById('configMinute').focus();
return false;
}
}else if(input == '*' || (input>=0 && input <=59)){
return true;
}else{
alert("Please enter numbers between 0 to 59 or '*' ==>4");
document.getElementById('configMinute').focus();
return false;
}
Thanks in advance
You could try a regex like
(?:(?:^|,)(?:[1-5]?\d|\*?\/59)\b)+$
It matches the beginning of the line (^) or a , followed by either a number, 0-59, or /59 optionally preceded by a *. And this pattern can then repeat any number of times, until the end of the line.
See it here at regex101.

Categories