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
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.