Search code examples
regexng-pattern

Add another regex to an existing one


I have the following 2 pattern :

https://codepen.io/anon/pen/OdZaBe

 /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!#$%\-_=+<>])[A-Za-z\d!#$%\-_=+<>]/;

https://codepen.io/anon/pen/ErLOOw

/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!#$%\-_=+<>]/

pattern 1 require a letter/number/special character, and pattern 2 just a number and a character.

I would like to add to this a pattern that disable any whitespace or full whitespace string: (?!\s*$)[\s\S]+$

I tried

/^(?=.*[A-Za-z])(?=.\S*$)(?=.*\d)[A-Za-z\d!#$%\-_=+<>]/;
/^(?=.*[A-Za-z])(?=.(?!\s*$)[\s\S]+$)(?=.*\d)[A-Za-z\d!#$%\-_=+<>]/;

but it doesn't work has expected.

ENDING result would be

pattern 1 require at least 1 letter/number/special character and not allow any whitespace

pattern 2 require at least 1 number and character and not allow any whitespace


Solution

  • Both patterns do not match a whitespace by itself. See https://regex101.com/r/FaQhfD/1 and https://regex101.com/r/IWWhSp/1

    But in in your code you have to repeat the character class at the end using a quantifier and assert the end of the string unsing an anchor $:

    $scope.thing = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d!#$%\-_=+<>]+$/;
    

    and:

    $scope.thing = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[!#$%\-_=+<>])[A-Za-z\d!#$%\-_=+<>]+$/;
    

    To prevent entering a whitespace at the end, you could use ng-trim="false", see ngTrim:

    <input type="text" ng-model="something" ng-pattern="thing" ng-trim="false" />
    

    Example of the updated codepens: update 1 and update 2