So everything works in the following code, except for the validation of whether or not a password has a numerical digit. Can anyone see what may be wrong with my code here? It's acting like my password passes the test for numerical digits when it doesn't.
// Too short
//var password = "pass";
// Contains a space
// password = "Contains space";
// Doesn't use a digit
password = "my-password";
// Repeats first and last 3 chars
//password = "abc123abc";
// Strong password
// password = "StrongPassword1";
// See if function returns an error message or not
var message = testPassword(password);
if (message) {
console.log(message);
}
else {
console.log("Password accepted.");
}
function testPassword(password) {
var n = password;
// Returns true if n is a string with a single digit, false otherwise
var hasDigit = function isSingleDigit(n) {
var unicodeValue = n.charCodeAt(0);
return n.length === 1 && unicodeValue >= 48 && unicodeValue <= 57;
};
if (password.length < 6){
return "Password must be at least 6 characters.";
}
if (password.indexOf(" ") != -1){
return "Password may not contain a space.";
}
if (hasDigit === false){
return "Password must have at least one digit.";
}
if (password.substr(0, 3) === password.substr(-3)){
return "The password may not begin and end with the same 3 characters.";
}
// Everything is good
return "";
}
Console output:
Password accepted.
EDIT: Here was the fix. Thanks awesome community!
var n = password;
// Returns true if n is a string with a single digit, false otherwise
function isSingleDigit(n) {
var unicodeValue = n.charCodeAt(0);
return n.length === 1 && unicodeValue >= 48 && unicodeValue <= 57;
}
var hasDigit = isSingleDigit(n);
The variable hasDigit has the definition of the function itself and not the return value since it was never called.
Change your if statement to
if (hasDigit(n) === false){
return "Password must have at least one digit.";
}
Edit
However, I don't think the function would still work correctly as this function would only return true if the passwordis a single digit as opposed to a string containing at least one digit.
Related
I am trying to make a palindrome checker with the condition of having to use a while loop.
It's giving me a right headache!
it returns isPalindrome as false every time even if the word is a palindrome.
let word = prompt('Please Enter a word')
let reverse = word.split('').reverse().join('').toLowerCase();
i = 0
final = word.length
let isPalindrome = false
while (i < word.length) {
if(word[i] == reverse[i])
i++
if(i = word.length)
break;
else if (i !== word.length)
break;
}
if (i == word.length) {
isPalindrome == true
}
else if (true) {
isPalindrome == false
}
if (isPalindrome == true) {
window.alert('Your word is a palindrome')
}
else if (isPalindrome == false) {
window.alert('Your word is not a palindrome')
}
I have tried messing around with the == signs and changing the break;
it used to return as always palindrome, but now it always returns as not a palindrome
The idea is to compare the word with the reverse version of it and check every index to see if it matches.
If they all match the word is a palindrome (racecar && racecar)
If they do not match it is not (racer && recar)
The program should output the result
Many thanks!
Alternative: nibble off letters of the word from both sides and compare them until either there's one letter left (is palindrome) or they don't match (no palindrome):
const isPalindrome = word => {
const letters = word.toLowerCase().split("");
while (letters.length > 1) {
if (letters.shift() !== letters.pop()) {
// not a palindrome: break the loop
// by returning false
return false;
};
}
return true;
}
console.log(`racecar ${isPalindrome(`racecar`)}`);
console.log(`rotator ${isPalindrome(`rotator`)}`);
console.log(`carrace ${isPalindrome(`carrace`)}`);
console.log(`rotonda ${isPalindrome(`rotonda`)}`);
Basically, I want to change a person input from 0######### to (0#)########, the event im using is onblur
function numberChange(){
var check = document.getElementById("number").value;
var regCheck = /^[0-9]+$/;
if (check != 10 || !regCheck)
{
alert("Please input your 10 digit mobile number")
return false;
}
else if (check == 10 || regCheck)
{
return true;
}
}
Your regCheck should be ^\(0\d\)\d{8}$
Demo
Update :
This regex validates the number of characters, you can omit length check in your code :
function numberChange(){
var check = document.getElementById("number").value;
var re = new RegExp(/^\(0\d\)\d{8}$/);
if (re.test(check)) {
return true;
}
else {
alert("Please input your 10 digit mobile number")
return false;
}
}
This will check for 10 digits, first number is zero, and that all inputs are digits. Once all of that passes the code will add the '(' & ')' to it. This approach gives specific errors depending on how the user incorrectly entered the number.
<html>
<body>
Phone number: <input type="text" id="number" onblur="checkNumber()">
<script>
function checkNumber() {
var x = document.getElementById("number").value;
// Check for 10 digits.
if(x.length != 10) {
alert('The number must be 10 digits.');
return false;
}
// Make sure the first digit is 0.
if(x.charAt(0) != 0) {
alert('The first digit must be 0.');
return false;
}
// Make sure all digits are numbers and not characters.
if(isNaN(x) == true) {
alert('All digits must be numbers.');
return false;
}
// If here then everything else passed so add the '(' and ')' to the number.
document.getElementById("number").value = '(0' + x.charAt(1) + ')' + x.substring(2, 10);
}
</script>
</body>
</html>
I see other solutions to my question but none that help me.
I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.
Also, prompt the user again and again if anything other than a number is entered
Here's the code so far
When I enter a number, it keeps alerting me it is true or false but won't let me enter another.
How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1
function isPositive(num) {
var result;
if (num >= 0) {
result = true;
} else if (num < 0) {
result = false;
}
return result;
}
var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
alert(isPositive(num));
if (isNaN(num)) {
alert("No number entered. Try again");
num = parseInt(prompt("Enter a number"));
isPositive(num);
while (num != -1) {
alert(isPositive(num));
}
}
}
There's a few things wrong with your code, so here's a rewrite with comments:
function isPositive(num) {
// if something is true return true; else return false is redundant.
return num >= 0;
}
// when you want to keep doing something until a condition is met,
// particularly with user input, consider a while(true) loop:
var num;
while (true) {
num = prompt("Enter a number");
// check for null here
if (num === null) {
alert("No number entered. Try again.");
continue; // return to the start of the loop
}
num = parseInt(num, 10); // second argument is NOT optional
if (isNaN(num)) {
alert("Invalid number entered. Try again.");
continue;
}
// once we have a valid result...
break;
}
// the loop will continue forever until the `break` is reached. Once here...
alert(isPositive(num));
Math.sign(number)
which returns either a 1, -1 or 0
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
The number 0 is neither positive, nor negative! :P
function isPositive(num)
{
if(num < 0)
return false;
else
return true;
}
Or a simple way,
function isPositive(num)
{
return (num > 0);
}
You are testing if it isn't -1. Try this:
if(num < 0){
...IS NEGATIVE...
}else{
...IS POSITIVE...
}
This checks if it is less than or greater than 0.
var validatePassword = function(password) {
var upper = new RegExp(/^(?=.*[A-Z]).+$/),
lower = new RegExp(/^(?=.*[a-z]).+$/),
symbols = new RegExp(/^(?=.*(_|[^\w])).+$/),
numbers = new RegExp(/^(?=.*\d).+$/);
if((upper.test(password) && lower.test(password)) || (upper.test(password) && numbers.test(password)) || (upper.test(password) && symbols.test(password)) || (lower.test(password) && numbers.test(password)) || (lower.test(password) && symbols.test(password)))
{
return true;
}
else
{
alert('Invalid password')
}
}
validatePassword('Foo1!');
});
it only return true if any value is entered if i only enter one it returns me true
You should do:
var upper = new RegExp(/^(?=.*[A-Z]).+$/),
lower = new RegExp(/^(?=.*[a-z]).+$/),
symbols = new RegExp(/^(?=.*(_|[^\w])).+$/),
numbers = new RegExp(/^(?=.*\d).+$/);
to:
var upper = /^(?=.*[A-Z]).+$/,
lower = /^(?=.*[a-z]).+$/,
symbols = /^(?=.*(_|[^\w])).+$/,
numbers = /^(?=.*\d).+$/;
Your regex is already a regex. You don't need to use new RegExp("patter","flag");
Let's simplify the logic first
var upper = new RegExp(/^(?=.*[A-Z]).+$/),
lower = new RegExp(/^(?=.*[a-z]).+$/),
symbols = new RegExp(/^(?=.*(_|[^\w])).+$/),
numbers = new RegExp(/^(?=.*\d).+$/);
Above can be simplified
var upper = /[A-Z]/, // means it contains uppercase
lower = /[a-z]/, // means it contains lowercase
symbols = /[\W_]/, // means it contains non-word character or underscore
numbers = /\d/; // means it contains number
Also here
// means must have (upper AND lower) OR ((upper OR lower) AND (symbol OR number))
if(
(upper.test(password) && lower.test(password)) ||
(upper.test(password) && numbers.test(password)) ||
(upper.test(password) && symbols.test(password)) ||
(lower.test(password) && numbers.test(password)) ||
(lower.test(password) && symbols.test(password))
)
Above can be simplified
// means must have (upper AND lower) OR ((upper OR lower) AND (symbol OR number))
if(
(upper.test(password) && lower.test(password)) ||
((upper.test(password) || lower.test(password)) &&
(symbols.test(password) || symbols.test(password)))
)
Since it can be (upper AND lower) only
upper.test(password) && lower.test(password)
It can be tested with
var upandlow = /[a-z][A-Z]|[A-Z][a-z]/;
Since it must have (upper OR lower), then it can also be checked in ONE step
var upperlower = /[a-zA-Z]/; // means it contains uppercase OR lowercase
Since it must have (symbol OR number), then it can also be checked in ONE step
var symbolsnumbers = /[\d\W_]/; // means it contains number OR non-word OR underscore
Now the whole function can be simplified
var validatePassword = function(password) {
var upandlow = /[a-z][A-Z]|[A-Z][a-z]/,
upperlower = /[a-zA-Z]/,
symbolsnumbers = /[\d\W_]/;
if (
upandlow.test(password) ||
(upperlower.test(password) && symbolsnumbers.test(password))) {
console.log('true');
return true;
}
else {
//alert('Invalid password');
console.log('Invalid');
}
}
validatePassword('Foo!');
Here is the fiddle
Good luck
:)
Based on your comment I've updated my answer:
The password needs to match at least two out of 4 conditions and have 8 characters to be true
var validatePassword = function(password) {
var numero = 0;
//check if a digit is present
if(/(?=.*?[\d]).*$/.test(password)) {
numero++;
}
//check if a uppercase letter is present
if(/(?=.*?[A-Z]).*$/.test(password)) {
numero++;
}
//check if a lowercase letter is present
if(/(?=.*?[a-z]).*$/.test(password)) {
numero++;
}
//check if a special character is present
if(/(?=.*?(_|[^\w])).*$/.test(password)) {
numero++;
}
//check if at least 8 characters are present
if (/^(?=.{8,}).*$/.test(password)) {
var length = true;
}
if( numero>=2 && length){
alert('Valid password');
console.log(numero);
return true;
}
else
{
alert('Invalid password');
console.log(numero);
}
}
validatePassword('foo4ogD!');
http://jsfiddle.net/tuga/S57Bb/4/
I’d like use jquery function that validate a input field. This input field must be used for entering 11 digit numbers that start with 0.
I tried some function but doesn’t work!
function check(mob) {
var firstnum = mob.substring(1);
alert(firstnum);
if (firstnum != "0" || mob.lenght != 11)
return false;
else
return true;
}
function check(mob) {
return mob.substring(0, 1) == '0' && mob.length == 11;
}
String Method Reference
If you want to check is it 11 digit, you should use RegExp
function check(mob) {
return mob.match(/^0\d{10}$/) != null;
}
You need to use .charAt(0) to get the first character of a string. .substring(1) will return the rest of the string minus the first character.
"01234567890".substring(1) = "1234567890"
"01234567890".charAt(0) = "0"
"01234567890".length = 11 (assuming that you have spelled "length" correctly in your code)
Edit: Since you also need to check for digits, you could use a regular expression to verify this (although the whole check could also be done with a regex)
The completed function could therefore be simplified to just:
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && /^\d+$/.test(mobileNumber);
}
Or without the regex
function isValidMobile(mobileNumber) {
return mobileNumber.charAt(0) == 0 && mobileNumber.length === 11 && !isNaN(mobileNumber);
}
if (firstnum >= 1 || mob.lenght <= 11) //lenght spell wrong
change to
if (firstnum >= 1 || mob.length<= 11)
you can give it a try
function check(mob) {
var num = parseInt(mob);
if (mob+'' == '0'+num && mob.length == 11)
return true;
else
return false;
}
here what I am doing is that parseInt will give you exact same number without 0 if all characters are numbers, so in the condition I am just adding 0 in starting and checking with mobile number , it will do 2 validation in once , all are number starts with 0 and next validation is for length
Try using a simple regex as below
function check(mob) {
return /^0\d{10}$/.test(mob)
}
function check(mob) {
if(!isNaN(mob)){ // or use parseInt
var firstnum = mob.charAt(0);
alert(firstnum);
if (firstnum != "0" || mob.length != 11) {
return false;
} else {
return true;
}
}
}