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
escaping
/like\/is a good practise but inside of char class, not necessary.
the*must be changed to+. because*will also matchnull.
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>
function checkValidity(input){
var onlyAlphaNum = /^[a-z0-9//]+$/
return onlyAlphaNum.test(input);
}
var message = $('#message').val();
if(!checkValidity(message)){
$('#message').focus();
alert('invalid message');
}
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.