I am new to JavaScript and I'm currently creating a password generator for a project. I am running into a problem where when the user is prompted with confirm messages to select their ideal password criteria. I want to return an alert message to the window with a loop function if they don't choose at least one option. Here is what I have so far.
// function: when you click on generate button it prompts messages to select password criteria.
var generateBtnPrompt = function () {
var confirmNumber = confirm("Click 'OK' to generate numbers in your password");
var confirmLowerCase = confirm("Click 'OK' to generate lowerCase characters in your password");
var confirmUpperCase = confirm("Click 'OK' to generate upperCase characters in your password");
var confirmSymbols = confirm("Click 'OK' to generate symbols characters in your password");
//parseInt convert a string into an integer
var charLength = parseInt(prompt("How many characters would you like your password to be? Please choose a number from (8-128)"));
};
You can use the Logical OR operator (||) to check that at least one of the variables are true.
MDN Web Docs:
The logical OR (||) operator (logical disjunction) for a set of
operands is true if and only if one or more of its operands is true.
And recursion to re-run the function if none of the variables are true.
Like this:
if (!(confirmNumber || confirmLowerCase || confirmUpperCase)) {
alert("You need to pick at least one!");
return generateBtnPrompt()
}
Full code:
var generateBtnPrompt = function () {
var confirmNumber = confirm("Click 'OK' to generate numbers in your password");
var confirmLowerCase = confirm("Click 'OK' to generate lowerCase characters in your password");
var confirmUpperCase = confirm("Click 'OK' to generate upperCase characters in your password");
var confirmSymbols = confirm("Click 'OK' to generate symbols characters in your password");
if (!(confirmNumber || confirmLowerCase || confirmUpperCase)) {
alert("You need to pick at least one!");
return generateBtnPrompt()
}
var charLength = parseInt(prompt("How many characters would you like your password to be? Please choose a number from (8-128)"));
};
generateBtnPrompt()
Related
i want to validate a password field with the following conditions:
One uppercase character
One lowercase character
One number
One special character
Eight characters minimum
If the password input is correct i want to make the pass field green if not it should be red.
I tried with this code but doesnt work:
let password = document.querySelectorAll(".control-group")[3];
password.addEventListener("focusout", () => {
let inp = password.value;
if (
inp.match(/[a-z]/g) &&
inp.match(/[A-Z]/g) &&
inp.match(/[0-9]/g) &&
inp.match(/[^a-zA-Z\d]/g) &&
inp.length >= 8
) {
password.style.backgroundColor = "green";
} else {
password.style.backgroundColor = "red";
}
});
The code you provided is not working due to the fact that
inp.match(/[a-z]/g) && inp.match(/[^a-zA-Z\d]/g)
is just "false". You are telling there "if it contains alphabetic characters as well as it doesn't contains any", which is some sort of
let i = 0;
if (i == 1) {...}
As I said on one of the comments of your question, just search for another solution, like the one that #harsh-saini said.
Output of match() is not true or false, but the match thing like str or int or if it wrong it will show null. So in your case better use "if your case (if input.match() != null) as true". There is the example !
var input = "GoodMorning Sir"
if (input.match(/[0-9]/g) != null){
console.log("there are number here")
} else if (input.match(/[A-Z]/g) != null){
console.log("there are uppercase here")
}
//this is your if else code, try to console.log your condition
//as you can see it wont giving output true or false
console.log(input.match(/[A-Z]/g)) // ["G", "M" , "S"]
I am a beginner experimenting with some basic Javascript.
My goal is to show a (1.) prompt message (requesting a name) followed by an (2.) alert based on the prompt input. If the prompt input is a valid name (string) then an alert box should appear with text "thank you" + name. Else the alert should appear with the text "you didn't enter a valid name".
The 1. prompt message is working, however, the 2. alert message shows me the same text whether i enter a name/text or a number. In other words the alert message is not distinguishing between text string or number and is always showing the text "thank you" + name.
this is my code:
function EnterName() {
var name = prompt("Enter your name here:");
if (typeof name === "string") {
alert("thank you " + name);
} else if (typeof name === "number") {
alert("you didn't enter a valid name");
}
}
console.log(EnterName());
Would appreciate any insights in how to make the alert box show "you didn't enter a valid name" when a number is entered in the prompt box.
Thanks.
Prompt always returns a string, you could try to convert it to a number and then check to see if it NaN's on you which means it's a string. It would be better to use a regexp here though. You may also want to return the name if you are logging it.
function EnterName() {
var name = prompt("Enter your name here:");
var isNum = !isNaN(Number(name));
if (!isNum) {
alert("thank you " + name);
} else {
alert("you didn't enter a valid name");
}
return name;
}
console.log(EnterName());
You always enter strings into prompts. SO you can try to make it a int below and if it succeeds then give an error message otherwise say hello.
function EnterName() {
var name = prompt("Enter your name here:");
if(parseInt(name)) {
alert("you didn't enter a valid name");
}
else if (!parseInt(name)) {
alert("thank you " + name);
}
}
prompt method parameters type are alway String, no matter what you enter, your condition will always true :
//text & defaultText types are String
`prompt(text, defaultText)`
So you need to change your condition. One solution is using regex for example you can change your code to this :
function EnterName() {
var name = prompt("Enter your name here:");
!name.match(/^\d+$/) ?
alert("thank you " + name)
:
alert("you didn't enter a valid name");
}
console.log(EnterName());
Basically !name.match(/^\d+$/) will check if input data is number or not and based on that will show the alert messages.
https://jsfiddle.net/6mxL59k0/1/
So, one thing I want to emphasize is how you are approaching solving this problem. You are looking at your problem thinking, "If I type in a number, this should be false! Why isn't it working?!". The reason why is because prompt will always return a value that is typed to a string. You are looking to see if there is a number or an int depending on the language.
So, we can break this into two problems. See if this guy is a string, see if that string contains a number
The code below shows a great way to do that using two functions
function enterName() { // Javscript functions should always start with a lowercase unless it is a function express and can be invoked using the `new` keyword
var name = prompt("Enter your name here:");
if (!checkIfContainsNumber(name)) {
alert("thank you " + name);
} else { // if f we dont have a number, we have a valid name, otherwise we are invalid!
alert("you didn't enter a valid name");
}
}
So we have our main function, it takes in the promp which always returns a string
// this solves problem 2, seeing if we have a number inside of our string
function checkIfContainsNumber(myString) {
return /\d/.test(myString);
}
enterName();
our second function checkIfContainsNumber solves part 2 of our problem using a regex expression that matches for a digit (d in this case)
I was able to create a script to validate IP address correctly like this,
var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if(g_form.getValue('src_nw_ip_hdcc').match(ipformat)){
return true;
}else{
alert("You have entered an invalid Network IP Address!");
return false;
}
The results was great but until then they made a unusual request that they require me to validate user enter 3 digits and not allow enter 1 or 2 digits like for example,
user can't enter 115.42.150.37, instead must enter 115.042.150.037. How can I add verify to ensure they enter 3 digits?
You can do it by removing alls "?" in the regex.
This way your regex requires 3 digits every time and accepts things like 192.168.001.001
^(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])$
In your code it has [01]?[0-9][0-9]. It says it can have a leading 0 or 1 or not followed by two numbers. Simple fix is to remove the ? where it makes the 0 and 1 optional
/^(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])\.(25[0-5]|2[0-4][0-9]|[01][0-9][0-9])$/
I think this regex will do the job. Hope this helps.
const regex = /^(((25[0-5])|(2[0-4][0-9])|([01][0-9]{2}))\.){3}((25[0-5])|(2[0-4][0-9])|([01][0-9]{2}))$/g;
console.log('Should match');
console.log('255.255.255.255'.match(regex));
console.log('012.000.255.001'.match(regex));
console.log('000.000.000.000'.match(regex));
console.log('Should not match');
console.log('255.255.255.'.match(regex));
console.log('255.255.255.-1'.match(regex));
console.log('.255.255.'.match(regex));
console.log('255.275.255.'.match(regex));
console.log('255.275.255.1'.match(regex));
console.log('25.5.55.1'.match(regex));
You can use split() and every() in conjunction to get that validation work:
function checkIp(ip) {
var isCorrect = ip.split('.').every(addr => addr.length === 3);
if (isCorrect) {
return 'Ip address is correct';
}
return 'Ip address is incorrect';
}
var ip = '115.042.150.037';
console.log(checkIp(ip));
ip = '11.042.150.037';
console.log(checkIp(ip));
I want to filter multiple zip codes in an input, there should be at least 2 zip SEPARATED by a COMA, I am trying to validate them in javascript with the following code but it's now filtering, the submit send the form to the next page without error, anyone can help?
<script>
function validateMULTIZIP() {
if(!/\d{11,}/.test(document.zipad.textfield.value) && document.getElementById('single').checked==false))
{
alert( "There should be a least two Zip codes separated by a coma." );
document.zipad.textfield.focus() ;
return false;
}
return true;
}
</script>
This will check for two 5-digit numbers separated by a comma
^\d{5},\d{5}$
But, you said at least two, so that means it needs to be a little more flexible to accommodate more. If the user enters 12345,12345,12345 it needs to be valid.
^\d{5}(?:,\d{5})+$
What if the user adds a space after the comma? Such as 12345, 12345. This is perfectly valid, so let's make sure our validator allows that.
^\d{5}(?:,\s*\d{5})+$
Oh, and zip codes can have an optional -1234 ending on them, too (known as ZIP+4. Maybe you want something like this
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$
Now strings like this would be valid
12345
12345, 12345,12345
12345, 12345-9999, 12345
As a bonus, let's say 12345, 12345 is invalid because it has the same zip code twice. Here's how we'd fix that
(?:(\d{5}),?)(?!.*\1)
And here's the ZIP+4 version
(?:(\d{5}(?:-\d{4})?),?)(?!.*\1(?!-))
This one has a little added complexity because of possibility of (e.g.,) 12345, 12345-9999. This is valid but because 12345 can appear more than once, it makes sure that a 5-digit zip code can't be invalidated by a unique 9-digit zip code.
Note these duplicate-checking regexps do not enforce the minimum of two unique zip codes. If you want to check for duplicates you'd need to combine the two.
var valid5DigitZipCodes = function(str) {
if (! /^\d{5}(?:,\s*\d{5})+$/.test(str)) {
alert("You need at least 2 zip codes");
return false;
}
else if (! /(?:(\d{5}),?)(?!.*\1)/.test(str)) {
alert("You entered a duplicate zip code");
return false;
}
return true;
};
And here's the ZIP+4 variant if you want to support that
var valid9DigitZipCodes = function(str) {
if (! /^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$/.test(str)) {
alert("You need at least 2 zip codes");
return false;
}
else if (! /(?:(\d{5}(?:-\d{4})?),?)(?!.*\1(?!-)).test(str) {
alert("You entered a duplicate zip code");
return false;
}
return true;
};
Assuming (from your code) that ZIP code contains five digits and no other characters, you could use:
/\d{5},\d{5}/.test(document.zipad.textfield.value)
You regex: \d{11,} means "any digit, eleven times or more", that's why it's broken.
Another Solution without using regex would be splitting zip Codes by comma then check for the size of the resulting array.
Sample code:
<input type="text" id="in"></input>
<button onclick="validate()">Click</button>
JS
function validate() {
var inp = document.getElementById("in");
var content = inp.value;
var correct = validateZipString(content);
if (correct) {
alert("ok");
} else {
alert("not ok");
}
}
function validateZipString(zipString) {
var zipCodes = zipString.split(',');
if (zipCodes.length < 2) return false;
for (var i = 0; i < zipCodes.length; i++) {
//validate each zipCode if required
}
return true;
}
here is a working jsfiddle http://jsfiddle.net/VcNd9/3/
For anyone else interested in the variant that also matches 1 zip or more rather than two or more. Simply change the + quantifier for * at the end of the expression.
From:
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)+$
To:
^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$
For example:
<input type="text" inputmode="numeric" pattern="^\d{5}(?:-\d{4})?(?:,\s*\d{5}(?:-\d{4})?)*$">
i have to create a regular expression for password in java script with the following criteria
1. The password should contain atleast one alphabet either upper case or lower case
2. It should contain atleast one number
3. It should contain atlease one special character(`,~,!,#,#,$,%,^,&,*,_,+,=)
var userpw = "musSTER123#";
var invalid = false;
if(!userpw.match(/\d/) || !userpw.match(/[a-zA-Z]/) || !userpw.match(/['~!##$%&*_+=]/))
invalid = true;
alert('pw is valid?' + !invalid);
Use these regexps:
[a-zA-Z] for at least one letter
[0-9] for at least one digit
['~!##$%&*_+=^] for at least one of the special characters you mentioned OR
[^a-zA-Z0-9] for at least one character that is neither a letter nor a digit
But even better would be to support single-sign-on with OpenID, SSL client certificates or a way to make the browser store a long password in its password storage without even showing it to the user (maybe some password input that's prefilled by javascript and hidden with CSS).
Don't require strong passwords. They are fool's gold. Yes, a strong password is better than a weak one, all other things being equal. But all other things are rarely equal. A strong password is more likely than a weak one to end up on a post-it note stuck to the user's monitor.
A far better defence is a good lock-out policy. A system that does nothing more than disallow passwords containing dictionary words, but locks IP addresses out for one hour after three failed login attempts will still be over 99% secure after one year of constant battering by brute force. Also, you can make it much stronger by increasing the lock-out period for continued failed attempts.
These posts were helpfull here is a bit of code some of you may want to use at some point. This forces the user to input an Uppercase, Lowercase, Special character, and minimum of 8 characters in length. It also breaks it up and lets them know what exactly it is they are doing wrong.
<script type="text/javascript" language="javascript">
function validate() {
if (document.aspnetForm.PasswordValue.value == '') {
alert('Current Password is a required field!');
document.aspnetForm.PasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value == '') {
alert('New Password is a required field!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/\d/) == null) {
alert('Your new password must have a number!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/[a-z]/) == null) {
alert('Your new password must have an Upper and lower case letter!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/[A-Z]/) == null) {
alert('Your new password must have an Upper and lower case letter!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.match(/['~!##$%&*_+=]/) == null) {
alert('Your new password must have a special character i.e.(!##$%&*)');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value.length < 8) {
alert('Your new password must have a minimum of 8 characters!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
if (document.aspnetForm.NewConfirmPassword.value == '') {
alert('Confirm New Password is a required field!');
document.aspnetForm.NewConfirmPassword.focus()
return false;
}
if (document.aspnetForm.NewPasswordValue.value != document.aspnetForm.NewConfirmPassword.value)
{
alert('New password and Confirm New Password do not match!');
document.aspnetForm.NewConfirmPassword.focus()
return false;
}
if (document.aspnetForm.PasswordValue.value == document.aspnetForm.NewPasswordValue.value) {
alert('Your current password and new password are the same!');
document.aspnetForm.NewPasswordValue.focus()
return false;
}
}
</script>