2

This checks if one or more numbers are present in the string, if one ore more letters are in the string, and if the length is higher than 5.

is there a way to join them in a single regex?

var aliascheck = $('#alias').val();

if (!/\d/.test(aliascheck) || !/[a-z]+/.test(aliascheck) || (aliascheck.length < 5)){ 
    alert('you need to enter at least a letter, a number...);
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Tapioca
  • 309
  • 3
  • 7

3 Answers3

1

You can use this

^(?=.*\d)(?=.*[a-z])(?=.{5,}).*$
  • ^ - Start of string
  • (?=.*\d) - condition for atleast one digit
  • (?=.*\[a-z]) - condition for atleast one letter
  • (?=.{5,}) - condition for length 5 or greater
  • .* - Match anything except new line
  • $ - End of string

let testFunc = (str) => /^(?=.*\d)(?=.*[a-z])(?=.{5,}).*$/i.test(str)

console.log(testFunc('12345'))
console.log(testFunc('1'))
console.log(testFunc('1Abcf'))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

You can try this

 /(?=[^\d])|(?=[^a-z]+)|(?=.{5})/g.test()
0

I will use next regular expression that uses positive lookaheads:

/^(?=.*[a-zA-Z])(?=.*[0-9])(?=.{5,})/

Example:

$("#testBtn").click(function()
{
    var aliascheck = $('#alias').val();

    if (!/^(?=.*[a-zA-Z])(?=.*[0-9])(?=.{5,})/.test(aliascheck))
    { 
        console.log("Test failed");
    }
    else
    {
        console.log("Test success");
    }    
});
.as-console {background-color:black !important; color:lime;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="alias" type="text" placeholder="Insert Alias">
<button id="testBtn">Test</button>
Shidersz
  • 16,846
  • 2
  • 23
  • 48