REGEX - must contain alphanumeric and slash

后端 未结 3 986
执笔经年
执笔经年 2021-01-27 03:27

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

3条回答
  •  清酒与你
    2021-01-27 04:27

    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');
    }
    
    

    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.

提交回复
热议问题