Regex for alphanumeric string with at least 1 number and 1 character and a fixed length of 11

I need regex to match an alphanumeric string exact 11 characters long but the value must contain at least both 1 character and 1 number.

Used a combination of Regex for alphanumeric with at least 1 number and 1 character

i.e. /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/

and What is the regex to match an alphanumeric 6 character string?

i.e. ^[a-zA-Z0-9]{6,}$

by using OR (||) operator like this

//regex code
var str = "";
if ($.trim($("input[id$='txtBranchName']").val()) != "")
    str = $.trim($("input[id$='txtBranchName']").val());
var reg_exp = /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i; // /^[a-zA-Z0-9]{11,}$/;//^(\d)(?:\1+)?$/; // new RegExp('([0-9]){6}');
var reg_exp2 = /^[a-zA-Z0-9]{11,11}$/;
if (!reg_exp.test(str) || !reg_exp2.test(str)) {
    $("span[id$='lblError']").css("color", "red");
    $("span[id$='lblError']").html($("span[id$='lbl_PayeeInformation_IFSCNo']").html()).show();
    $("input[id$='txtBranchName']").focus();
    returned = false;
    return false;
}
//end regex code

but it would be great if i get it in one regex.

Answers:

Answer

You need to combine both and use {11} for exact 11 characters match.

/^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9]{11}$/

Where :

  1. (?=.*\d) assert that the position follows a digit at any position(where \d is equivalent to [0-9]).
  2. (?=.*[a-zA-Z]) assert that the position follows an alphabet at any position.
  3. [a-zA-Z0-9]{11} matches only when the length is 11 characters and within the character class.
  4. ^ and $ are start and end anchors which help to check whole string.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.