15
votes

Can anyone help me with a regex to allow atleast one special character, one uppercase, one lowercase.

This is what I have so far:

 ^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

but it seems to match the characters only in the order "special character", "uppercase", "lowercase".

Any help is greatly appreciated

5
Any effort on your part is also greatly appreciated. This has been asked so many times...did you do any searching at all?Tim Pietzcker
regular-expressions.info is a great place to start.Felix Kling
yes i did ! and this is what i have got ^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$ ..it allows all of them but only in if they are entered in that order like spl char, Uppercase, lower case. Anywhere in between, it doesn't take!Thank you!Sweta
1 liner RegEx is not magical all the time.Shiplu Mokaddim
Which language are you using?Tim Pietzcker

5 Answers

28
votes

Your regex

^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

should actually work just fine, but you can make it a lot better by removing the first .*:

^(?=.{8,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$

will match any string of at least 8 characters that contains at least one lowercase and one uppercase ASCII character and also at least one character from the set @#$%^&+= (in any order).

7
votes

Here is a function you can use.

function checkRegex(string) {
    var checkSpecial = /[*@!#%&()^~{}]+/.test(string),
        checkUpper = /[A-Z]+/.test(string),
        checkLower = /[a-z]+/.test(string),
        r = false;

        if (checkUpper && checkLower && checkSpecial) {
            r = true;
        }

        return r;

        }

and then check if it's true or false.

var thisVal = document.getElementById('password').value;
var regex = checkRegex(thisVal);

If var regex is true then the condition satisfied.

4
votes

It can be done quickly by 3 regular expression.

function check($string){
   return    preg_match("/[`!%$&^*()]+/", $string) 
          && preg_match("/[a-z]+/", $string) 
          && preg_match("/[A-Z]+/", $string) ;
}

Dont forget to tweak the list of special characters. Because I dont know what characters you think are special.

I believe wasting a lot of time on a single line regex while you are not expert will not increase your productivity. This 3 regex solution will do just fine. It saves time.

0
votes

If you want the output like the image below :

Password Validator

You can use the dynamic custom component below :

import { Component, Input, OnInit, EventEmitter, Output, OnChanges } from '@angular/core';
import { RegExpValidator } from '../../classes/reg-exp-validator';

@Component({
  selector: 'app-reg-exp-validator',
  template: `
       <div *ngFor="let regExp of regExps" style='text-align: left'>
          <div>
            <i *ngIf="!regExp.isOptional" [ngStyle]="{'color': isValidExp(regExp) ? 'green' : 'red'}"
               [className]="isValidExp(regExp)? 'pi pi-check-circle' : 'pi pi-times-circle'">
              </i>
            <i *ngIf="regExp.isOptional" [ngStyle]="{'color': isValidExp(regExp) ? 'green' : 'orange'}"
               [className]="isValidExp(regExp)? 'pi pi-check-circle' : 'pi pi-times-circle'">
              </i>
            {{regExp.message}}
          </div>
       </div> `
})
export class RegExpValidatorComponent implements OnInit, OnChanges {



  @Input() value: string;
  @Input() regExps: Array<RegExpValidator>;

  @Output() onChange: EventEmitter<boolean> = new EventEmitter();

  constructor() { }

  ngOnChanges(): void {
    this.validateExpressions();
  }

  ngOnInit() {   
  }

  isValidExp(regExp) {
    if (regExp.isValid)
      return regExp.isValid;
  }

  initiValue() {
    this.value = this.value == undefined ? "" : this.value;
  }


  validateExpressions() {
    this.initiValue();
    let isInVlaidExpression = false;
    this.regExps.forEach((regExp) => {
      regExp.isValid = this.testRegExpression(regExp.regExpression);
      if (!regExp.isValid && !regExp.isOptional) {
        isInVlaidExpression = true;
      }
    });

    this.onChange.emit(isInVlaidExpression);
  }

  testRegExpression(regExpression: RegExp) {
    return regExpression.test(this.value);
  }
}

where

regExps

input array class is

export class RegExpValidator {
 regExpression: RegExp;
 message: string;
 ordinal: number;
 isValid: boolean = false;
 isOptional: boolean; }
  • After you define it, you can use it in your target component by following the two steps below :

    1- Define the first input parameters which is array of regular expressions itself , validation message and if it is optional or not as below :

    DefineRegExpressions(){
    let minPasswordLengthSixCharacters = new RegExpValidator();
    minPasswordLengthSixCharacters.message = " The password should be at least 6 charcters";
    minPasswordLengthSixCharacters.regExpression = /^.{6,}$/;
    minPasswordLengthSixCharacters.isOptional = false;
    
    let containsDigit = new RegExpValidator();
    containsDigit.message = "The password should contains at least 1 digit";
    containsDigit.regExpression = /\d/;
    containsDigit.isOptional = false;
    
    let containsLowerCharacter = new RegExpValidator();
    containsLowerCharacter.message = "The password should contains at least 1 lower charcter";
    containsLowerCharacter.regExpression = /.*[a-z].*/;
    containsLowerCharacter.isOptional = false;
    
    let containsUpperCharacter = new RegExpValidator();
    containsUpperCharacter.message = "The password should contains at least 1 upper charcter";
    containsUpperCharacter.regExpression = /.*[A-Z].*/;
    containsUpperCharacter.isOptional = false;
    
    let containsSymbol  = new RegExpValidator();
    containsSymbol.message = "The password contains at least 1 symbol @!#%&()^~{}";
    containsSymbol.regExpression = /[*@!#%&()^~{}]+/;
    containsSymbol.isOptional = true; }
    

then define the first input and add all the defined expressions declaration above to it:

  regExps = Array<RegExpValidator>();
    this.regExps.push(minPasswordLengthSixCharacters);
    this.regExps.push(containsDigit);
    this.regExps.push(containsLowerCharacter);
    this.regExps.push(containsUpperCharacter);
    this.regExps.push(optional);

2- Finally add to your target component HTML the below code :

  <app-reg-exp-validator [value]="password"
                                   [regExps]="regExps"
                                   (onChange)="onChangeRegExpValidator($event)">
            </app-reg-exp-validator>

the value input refer to the target input to validate in our case it is the password and the onChange is output from custom componet that you can use to know if all validation is valid or not.

0
votes

A more generic password/text validation where you can choose the number for characters to be allowed in each category.

var regularExpression = new RegExp("^^(?=.*[A-Z]{"+minUpperCase+",})" +
    "(?=.*[a-z]{"+minLowerCase+",})(?=.*[0-9]{"+minNumerics+",})" +
    "(?=.*[!@#$\-_?.:{]{"+minSpecialChars+",})" +
    "[a-zA-Z0-9!@#$\-_?.:{]{"+minLength+","+maxLength+"}$");
if (pswd.match(regularExpression)) {
    //Success
}