javascript regular expression for atleast one number and one uppercase letter

Go To StackoverFlow.com

1

what would be the regular expression to check if a given string contains atleast one number and one uppercase letter? Thanks in advance

I am doing like this

function validate_pass{
var var_password = document.getElementById("npassword").value;
else if (!(/^(?=.*\d)(?=.*[A-Z]).+$/).test(var_password))){
    msg = "Password should contain atleast.";

    showErrorMsgPassword(msg);
    $('#npassword').val('');
    $('#cpassword').val('');
    return false;
  }

else return true;
2012-04-04 02:31
by pri_dev
like /[0-9]+[A-Z]+/ or /[0-9]+[A-Z]/ - mshsayem 2012-04-04 02:34
You need to provide more info, such as examples of what you want to match and what you want to not match. You've given nothing here that makes your question possible to answer. Please edit to improve it so people can help you. Thanks. : - Ken White 2012-04-04 02:42
the digit & uppercase can appear anywhere is the strin - pri_dev 2012-04-04 02:55
You already have one - Justin Morgan 2012-04-04 03:11


1

It's been a while since I've done this, and I'm fairly certain there is a more efficient way than this. You will need to use positive lookaheads, but there should be a way to remove the wildcards from within them:

This regex (/^(?=.*[A-Z])(?=.*\d).*$/) will return the entire password if it matches the criteria.

('a3sdasFf').match(/^(?=.*[A-Z])(?=.*\d).*$/);

2012-04-04 03:02
by david


2

If the desire is to test a string to see if it has a least one digit and at least one uppercase letter in any order and with any other characters allowed too, then this will work:

var str = "abc32Qdef";
var re = /[A-Z].*\d|\d.*[A-Z]/;
var good = re.test(str);​

Working demo with a bunch of test cases here: http://jsfiddle.net/jfriend00/gYEmC/

2012-04-04 02:49
by jfriend00
You could use .test method of the Regex object - xdazz 2012-04-04 02:52
@xdazz - I switched to .test() - jfriend00 2012-04-04 03:00


0

Like below:

/(\d.*[A-Z])|([A-Z].*\d)/

To test a string matched or not:

var str = "abc32dQef";
var is_matched = /(\d.*[A-Z])|([A-Z].*\d)/.test(str);
2012-04-04 02:37
by xdazz
@mshsayem Have you tried /(\d.*[A-Z])|([A-Z].*\d)/.test("abc32dQef")? Note: if you want to match the ending, you should use $ - xdazz 2012-04-04 02:50