REGEX - must contain alphanumeric and slash

后端 未结 3 971
执笔经年
执笔经年 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:05

    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.

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

    0 讨论(0)
  • 2021-01-27 04:15

    function checkValidity(input){
    	var onlyAlphaNum = /^[a-z0-9//]+$/
    	return onlyAlphaNum.test(input);
    }
    
    var message = $('#message').val();
    if(!checkValidity(message)){
    	$('#message').focus();
        alert('invalid message');
    }

    0 讨论(0)
  • 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');
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="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.

    0 讨论(0)
提交回复
热议问题