as3 regular expression to validate a password - regex

I have a form that asks for a password and I want to validate if the password has at least eight characters, and of these eight characters at least two must be numbers and two must be letters in any order. I'm trying with this:
function validatePassword():void
{
var passVal:String = pass.text;
if(validPass(passVal))
{
trace("Password Ok");
sendForm();
}
else
{
trace("You have entered an invalid password");
}
function validPass(passVal:String):Boolean{
var pw:RegExp = /^?=.{8,}[A-Za-z]{2,}[0-9]{2,}/;
return(pw.test(passVal));
}
}
But it doesn't work. What I'm doing wrong?
Any help would be really appreciated!

use this pattern ^(?=.{8})(?=(.*\d){2})(?=(.*[A-Za-z]){2}).*$
^ anchor
(?=.{8}) look ahead for at least 8 characters
(?=(.*\d){2}) look ahead for at least 2 digits in any order
(?=(.*[A-Za-z]){2}) look ahead for at least 2 letters in any order
.*$ catch everything to the end if passed previous conditions

The problem is that your regex is forcing the numbers to follow the letters ([A-Za-z]{2,}[0-9]{2,}). While it is possible to write such a regex, I suggest using a simple length check and two regexes:
function validPass(passVal:String):Boolean{
if (passVal.length < 8)
return False;
var letterRegex:RegExp = /^.*?[A-Za-z].*?[A-Za-z].*?$/;
var numberRegex:RegExp = /^.*?\d.*?\d.*?$/;
return letterRegex.test(passVal) && numberRegex.test(passVal);
}

Related

Regex for the first 3 digits in a 6 digit number

I have items in a cms which have a 6-digit number.
The user can filter these item, via a input field,
by start typing a number.
const list = document.querySelector('#filter-wrap');
const searchBar = document.forms['search-kelim'].querySelector('input');
searchBar.addEventListener('keyup', function(e){
const term = e.target.value.toLowerCase();
const kelims = list.getElementsByClassName('filter-item');
Array.from(kelims).forEach(function(kelim){
let number = kelim.firstElementChild.textContent;
if(number.toLowerCase().indexOf(term) != -1 ){
console.log("Valid");
} else {
console.log("Invalid");
}
});
});
This is working, but it filters no matter where the digit
is occurring within the 6-digit number.
Aim is, it should only filter the first 3 starting digits, already starting with the first digit.
Meaning, if the user types 2, only the items starting with 2 are shown,
if the user then types 1, only the items starting with 21 are shown.
(the same for the third digit, typing 214 matches only the items starting with 214)
instead of indexof i tried with regex, but cannot get it to work:
var re = new RegExp("^[0-9]+$");
if (re.test(term)) {
console.log("Valid");
} else {
console.log("Invalid");
}
also tried these regex:
var re = new RegExp("^[0-9]");
var re = new RegExp("^\d{3}[0-9]");
var re = new RegExp("/[0-9]{1}[0-9]{1}[0-9]{1}/");
i also tried with match but also no luck, (different syntax?)
UPDATE:
here are two codepens for better understanding:
Filter with indexof, working but for first 3 digits.
https://codepen.io/hhentschel/pen/LYNWKeK
Filter with Regex, i tried all different answers, which came up so far.
https://codepen.io/hhentschel/pen/yLOMmbw
Your number variables all start with a line break. You may easily check that if you add console.log("'"+number+"': number") in the code.
To fix the regex approach, you just need to trim the incoming strings:
var re = new RegExp("^"+term);
if (re.test(number.trim())) { // <-- HERE!
kelim.classList.add("block");
kelim.classList.remove("hide");
} else {
kelim.classList.add("hide");
kelim.classList.remove("block");
}
Just check whether the Index is 0:
if(number.toLowerCase().indexOf(term) == 0){
console.log("Valid");
} else {
console.log("Invalid");
}
So you know that the term is at the beginning of the number.
But if you want to use regex, you have to build a new pattern every time:
var re = new RegExp("^"+term);
if (re.test(number)) {
console.log("Valid");
} else {
console.log("Invalid");
}

Angular regex error

I'm creating a form in Angular that requires the rate field to take only numbers with 2 decimal places. My HTML is as follows:
<input type="number" class="form-control" (keypress)="_keyPress($event)" (ngModelChange)="Valuechange($event,salesorder,'Rate')" [ngModelOptions]="{standalone: true}" name="customerCode" #customerCode="ngModel" [(ngModel)]="salesorder._dto.rate" [style]="{'text-align':'right'}" />
On every keypress event I'm calling _keyPress() method as follows:
_keyPress(event: any) {
const pattern = /[0-9\+\.\ ]/;
let inputChar = String.fromCharCode(event.charCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
event.preventDefault();
}
}
The above regex works fine but does not restrict the number to 2 decimal places. I tried with various regex but could not implement the restriction to 2 decimal places. The last regex I used to do the same is as follows:
const pattern = /[0-9]+(.[0-9]{0,2})/;
I have no much idea about regex.
You can try following regex:
const pattern = /^[0-9]*\.[0-9]{2}$/
Or you may use shorthand character class \d instead of [0-9] i.e:
const pattern = /^\d*\.\d{2}$/
Description:
[0-9]{2}$ or \d{2}$ will make sure that there are exactly 2 numbers after decimal point.
You may replace * with + if there must be at least one number before point.
To restrict the decimal place to 2 digits, you could use {2}.
{0,2} means match zero, one or two times.
[0-9]+(\.[0-9]{2})
Note
This uses an unnecessary capturing group (\.[0-9]{2}) which could be written as \.[0-9]{2}
You could also use anchors to match from the beginning ^ to the end $:
^[0-9]+(\.[0-9]{2})$
or
^[0-9]+\.[0-9]{2}$
var pattern = /^[0-9]+(\.[0-9]{2})$/;
var inputs = [
"22.65",
"22.6",
"22.656"
];
for (var i = 0; i< inputs.length; i++) {
console.log(pattern.test(inputs[i]))
}

Regex password validator

I have the following rules for password validation:
at least 6 characters
at least 1 capital letter
How can I validate this with a RegEx?
Here is my pattern: ^(?=.*[0-9]+.*)(?=.*[a-zA-Z]+.*)[0-9a-zA-Z]{6,}$
The pattern above enforces also numbers ... which I don't need. However user can enter any other characters he/she wishes except that must contain one capital and be longer or equal to 6 characters.
You can try this:
^(?=.*?[A-Z]).{6,}$
DEMO
If you want to allow special characters as well then change it like
^(?=.*?[A-Z])(?=.*?[#?!#$%^&*-]).{6,}$
^(?=.*[A-Z])[\w-[_\]]{6,}$
This force to contains a capital letter with (?=.*[A-Z]) and allow alphanumeric : [\w-[_\]] (\w is [a-zA-Z0-9_] in which we remove the _
You can use this :
(?=.*[A-Z]).{8}
or If you want to full rule, can try this :
(?=[a-z]*[A-Z])(?=\D*\d)(?=.*[#?!#$%^&*-]).{8}
It might be better to evaluate the rules separately to provide feedback to user as to which rule failed to validate.
I suggest doing something like this instead: https://jsfiddle.net/hejecr9d/
// will store list of rules
var rules = []
// at least one capital letter rule
rules.one_capital_letter = {
fail_message: 'password needs at least one capital letter',
validate: function(password){
return /[A-Z]/.test(password)
}
}
// at least six letters rule
rules.at_least_six_letters = {
fail_message: 'password needs to have at least 6 characters',
validate: function(password){
return password.length >= 6
}
}
function validate_password(password) {
// goes through all the rules
for(rule in rules) {
if(!rules[rule].validate(password)) {
return {success: false, message: rules[rule].fail_message}
}
}
// return success after all rules are checked
return {success: true, message: 'password validated successfully'}
}
// Test if it works
var test_strings = ['abcd', 'Abcd', 'Abcdef']
for(i in test_strings) {
$('body').append(test_strings[i] + ': ' + validate_password(test_strings[i]).message + '<br>')
}

Regular expression needed for specific string in PHP

I need a regular expression to validate a string with the following conditions
String might contain any of digits space + - () / .
If string contain anything else then it should be invalid
If there is any + in the string then it should be at the beginning and there should at most one + , otherwise it would be invalid, if there are more than one + then it is invalid
String should be 7 to 20 character long
It is not compulsory to have all these digits space + - () / .
But it is compulsory to contain at least 7 digit
I think you are validating phone numbers with E.164 format. Phone number can contain many other format. It can contain . too. Multiple spaces in a number is not uncommon. So its better to format all the numbers to a common format and store that format in db. If that common format is wrong you can throw error.
I validate those phone numbers like this.
function validate_phone($phone){
// replace anything non-digit and add + at beginning
$e164 = "+". preg_replace('/\D+/', '', $phone);
// check validity by length;
return (strlen($e164)>6 && strlen($e164)<21);
}
Here I store $e164 in Db if its valid.
Even after that you can not validate a phone number. A valid phone number format does not mean its a valid number. For this an sms or call is generated against the number and activation code is sent. Once the user inputs the code phone number is fully validated.
You can do this in one regex:
/^(?=(?:.*\d){7})[0-9 ()\/+-][0-9 ()\/-]{6,19}$/
However I would personally do something like:
/^[0-9 ()\/+-][0-9 ()\/-]{6,19}$/
And then strip any non-digit and see if the remaining string is 7 or longer.
Let's try ...
preg_match('/^(?=(?:.*\d){7})[+\d\s()\/\-\.][\d\s()\/\-\.]{6,19}$/', $text);
Breaking this down:
We start with a positive look-ahead that requires a digit at least 7 times.
Then we match all the valid characters, including the plus.
Followed by matching all the valid characters without plus between 6 and 20 times.
A little more concise:
^\+?(?=(.*\d){7})[()/\d-]{7,19}$
'Course, why would you even use regular expressions?
function is_valid($string) {
$digits = 0;
$length = strlen($string);
if($length < 7 || $length > 20) {
return false;
}
for($i = 0; $i < $length; $i++) {
if(ctype_digit($string[$i])) {
$digits++;
} elseif(strpos('+-() ', $string[$i]) === false && ($string[$i] !== '+' || $i !== 0)) {
return false;
}
}
return $digits >= 7;
}

Regular Expression to find numbers with same digits in different order

I have been looking for a regular expression with Google for an hour or so now and can't seem to work this one out :(
If I have a number, say:
2345
and I want to find any other number with the same digits but in a different order, like this:
2345
For example, I match
3245 or 5432 (same digits but different order)
How would I write a regular expression for this?
There is an "elegant" way to do it with a single regex:
^(?:2()|3()|4()|5()){4}\1\2\3\4$
will match the digits 2, 3, 4 and 5 in any order. All four are required.
Explanation:
(?:2()|3()|4()|5()) matches one of the numbers 2, 3, 4, or 5. The trick is now that the capturing parentheses match an empty string after matching a number (which always succeeds).
{4} requires that this happens four times.
\1\2\3\4 then requires that all four backreferences have participated in the match - which they do if and only if each number has occurred once. Since \1\2\3\4 matches an empty string, it will always match as long as the previous condition is true.
For five digits, you'd need
^(?:2()|3()|4()|5()|6()){5}\1\2\3\4\5$
etc...
This will work in nearly any regex flavor except JavaScript.
I don't think a regex is appropriate. So here is an idea that is faster than a regex for this situation:
check string lengths, if they are different, return false
make a hash from the character (digits in your case) to integers for counting
loop through the characters of your first string:
increment the counter for that character: hash[character]++
loop through the characters of the second string:
decrement the counter for that character: hash[character]--
break if any count is negative (or nonexistent)
loop through the entries, making sure each is 0:
if all are 0, return true
else return false
EDIT: Java Code (I'm using Character for this example, not exactly Unicode friendly, but it's the idea that matters now):
import java.util.*;
public class Test
{
public boolean isSimilar(String first, String second)
{
if(first.length() != second.length())
return false;
HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
for(char c : first.toCharArray())
{
if(hash.get(c) != null)
{
int count = hash.get(c);
count++;
hash.put(c, count);
}
else
{
hash.put(c, 1);
}
}
for(char c : second.toCharArray())
{
if(hash.get(c) != null)
{
int count = hash.get(c);
count--;
if(count < 0)
return false;
hash.put(c, count);
}
else
{
return false;
}
}
for(Integer i : hash.values())
{
if(i.intValue()!=0)
return false;
}
return true;
}
public static void main(String ... args)
{
//tested to print false
System.out.println(new Test().isSimilar("23445", "5432"));
//tested to print true
System.out.println(new Test().isSimilar("2345", "5432"));
}
}
This will also work for comparing letters or other character sequences, like "god" and "dog".
Put the digits of each number in two arrays, sort the arrays, find out if they hold the same digits at the same indices.
RegExes are not the right tool for this task.
You could do something like this to ensure the right characters and length
[2345]{4}
Ensuring they only exist once is trickier and why this is not suited to regexes
(?=.*2.*)(?=.*3.*)(?=.*4.*)(?=.*5.*)[2345]{4}
The simplest regular expression is just all 24 permutations added up via the or operator:
/2345|3245|5432|.../;
That said, you don't want to solve this with a regex if you can get away with it. A single pass through the two numbers as strings is probably better:
1. Check the string length of both strings - if they're different you're done.
2. Build a hash of all the digits from the number you're matching against.
3. Run through the digits in the number you're checking. If you hit a match in the hash, mark it as used. Keep going until you don't get an unused match in the hash or run out of items.
I think it's very simple to achieve if you're OK with matching a number that doesn't use all of the digits. E.g. if you have a number 1234 and you accept a match with the number of 1111 to return TRUE;
Let me use PHP for an example as you haven't specified what language you use.
$my_num = 1245;
$my_pattern = '/[' . $my_num . ']{4}/'; // this resolves to pattern: /[1245]{4}/
$my_pattern2 = '/[' . $my_num . ']+/'; // as above but numbers can by of any length
$number1 = 4521;
$match = preg_match($my_pattern, $number1); // will return TRUE
$number2 = 2222444111;
$match2 = preg_match($my_pattern2, $number2); // will return TRUE
$number3 = 888;
$match3 = preg_match($my_pattern, $number3); // will return FALSE
$match4 = preg_match($my_pattern2, $number3); // will return FALSE
Something similar will work in Perl as well.
Regular expressions are not appropriate for this purpose. Here is a Perl script:
#/usr/bin/perl
use strict;
use warnings;
my $src = '2345';
my #test = qw( 3245 5432 5542 1234 12345 );
my $canonical = canonicalize( $src );
for my $candidate ( #test ) {
next unless $canonical eq canonicalize( $candidate );
print "$src and $candidate consist of the same digits\n";
}
sub canonicalize { join '', sort split //, $_[0] }
Output:
C:\Temp> ks
2345 and 3245 consist of the same digits
2345 and 5432 consist of the same digits