Skip to content Skip to sidebar Skip to footer

Regex - Must Contain Alphanumeric And Slash

I am trying to do a validation that an input field must contain alpha numeric and slash as its value. Eg: AA/AB/12314/2017/ASD The above shown is the example of the value that shou

Solution 1:

it must contain both alphanumeric and slash.

I understand that you may have 1+ alphanumeric symbols followed with at least 1 / followed with more alphanumeric symbols. You need to change the regex to /^[a-z\d]+(?:\/[a-z\d]+)+$/i:

var message = $('#message').val();
if (!/^[a-z\d]+(?:\/[a-z\d]+)+$/i.test($.trim(message)))
{
    $('#message').focus();
    alert('invalid message');
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="message"value="ASD/TD"/>

Details:

  • ^ - start of string
  • [a-z\d]+ - 1 or more letters or digits
  • (?:\/[a-z\d]+)+ - 1 or more sequences of
    • \/ - slash
    • [a-z\d]+ - 1 or more letters or digits
  • $ - end of string
  • /i - a case insensitive modifier, so that [a-z] could also match uppercase ASCII letters.

If you mean there must be a / and alphanumeric anywhere inside the string, use lookaheads:

/^(?=[a-z\d]*\/)(?=\/*[a-z\d])[a-z\d\/]+$/i
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

See the regex demo. Here, (?=[a-z\d]*\/) requires a / after 0+ alphanumerics, and (?=\/*[a-z\d]) requires an alphanumeric after 0+ slashes. [a-z\d\/]+ will match 1 or more alphanumeric or slashes.

Solution 2:

escaping / like \/is a good practise but inside of char class, not necessary. the * must be changed to +. because * will also match null. also remove the - otherwise - will also be matched.

functionvalidate(){
  var message = $('#message').val();

  if (/^[a-zA-Z0-9/]+$/.test($.trim(message)) == false){
      $('#message').focus();
     alert('invalid message');
  }
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textareaid="message"></textarea><buttononclick="validate();">Test</button>

Solution 3:

functioncheckValidity(input){
	var onlyAlphaNum = /^[a-z0-9//]+$/return onlyAlphaNum.test(input);
}

var message = $('#message').val();
if(!checkValidity(message)){
	$('#message').focus();
    alert('invalid message');
}

Post a Comment for "Regex - Must Contain Alphanumeric And Slash"