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>
Related
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()
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));
First i'd like to mention that i've been researching about this for few days and although i found some answers that should have been helpful i was unable to use them correctly due to the fact that i am not that much into programming yet and got no experience and might be missing something.
Straight to the point, i have a registration form and i need field validation i already have the one that validate email and empty fields for others but i need to add to the code a part that would reject numerical entries in name fields and alphabetical characters for ID field and to limit the length of a field.
Let's start with the Name field which i want to allow alphabetical characters only here is my current code:
{
var fn=document.forms["myForm"]["FirstName"].value;
if (fn==null || fn=="")
{
alert("First name must be filled out");
return false;
}
And that's my ID field which i want to limit to numerical entries only
var id=document.forms["myForm"]["ID"].value;
if (id==null || id=="")
{
alert("ID must be filled out");
return false;
}
I want to a couple of lines that would limit entries to a specific number of characters as well, how do i do that?
To check for a string length in Javascript you can use the .length method:
// this checks if the fn length is more than 10
if (fn.length > 10) {
}
To check if a value is numeric you can parse it and make sure that returns a valid output:
// This checks if id is not a valid integer
if (isNaN(parseInt(id)) {
}
To check if a value is alphabetical only you have to make sure the characters in it fall within the alphabets range, you can add a function that checks for that:
// This loops on every character of value and makes sure it is part of the letters string
function isAlphabetical (value) {
var letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (i = 0; i < value.length; i++) {
if (letters.indexOf(value.charAt(i), 0) == -1) {
return false;
}
return true;
}
}
And then call it from your if statement:
// This checks if fn is not alphabetical
if (!isAlphabetical(fn)) {
}
I am trying to figure out if a user has entered an email id or a phone number. Therefore i would like to check if the string starts with +1 or a number to determine if it is a phone number . If it is not either i come to the conclusion it is an email or i could check if it starts with a alphabet to be sure. How do i check this . I am horrible with regex if that is the soln .
You can do this with RegEx, but a simple if statement will work as well, and will likely be more readable. If an # character is not present in the string and the first character is a number, it is reasonable to assume it's a phone number. Otherwise, it's likely an email address, assuming an # is present. Otherwise, it's likely invalid input. The if statement would look like this:
if(yourString.indexOf("#") < 0 && !isNaN(+yourString.charAt(0) || yourString.charAt(0) === "+")) {
// phone number
} else if(yourString.indexOf("#") > 0) {
// email address
} else {
// invalid input
}
if (!isNaN(parseInt(yourstrung[0], 10))) {
// Is a number
}
Just do the following:
if ( !isNaN(parseInt(inputString)) ) {
//this starts with either a number, or "+1"
}
Might I suggest a slightly different approach using the regex email validation found here?
if(validateEmail(input_str)) {
// is an email
} else if(!isNaN(parseInt(input_str))) {
// not an email and contains a number
} else {
// is not an email and isn't a number
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
This way you can check a little more thoroughly on what the input actually is, rather than just guessing it's one or the other.
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})?)*$">