Reputation: 1117
I was trying to do simple input field validation to restrict some special characters,I got the following solution for that.
But I am unable to understand that what is happening in this ternary operator
var str = String.fromCharCode(e.charCode ? e.which : e.charCode);
Can anyone explain?please..
$(document).ready(function(){
$('#textarea').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z0-9 ,.!?]+$");
var str = String.fromCharCode(e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else {
alert("enter only valid string(123 abc , . ! ?)");
e.preventDefault();
return false;
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="col-xs-12">Reason<span class="requiredField">*</span></label> <textarea id="textarea" rows="2"></textarea>
Upvotes: 1
Views: 937
Reputation: 33933
A better solution would be to bind this character verification to more events.
And for browser compatibility, look for the char code in all possible event attribute.
And I added an exception for Enter, as it is a textarea
and user may want to change line.
$(document).ready(function(){
$('#textarea').on("keypress paste",function (e) {
var regex = new RegExp("^[a-zA-Z0-9 ,.!?]+$");
var charCode = e.which || e.charCode || e.keyCode;
if(charCode!=13){ // to allow [ENTER]
var str = String.fromCharCode(charCode);
if (regex.test(str)) {
return true;
}
else {
alert("enter only valid string(123 abc , . ! ?)");
e.preventDefault();
return false;
}
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="col-xs-12">Reason<span class="requiredField">*</span></label>
<textarea id="textarea" rows="2"></textarea>
Upvotes: 1
Reputation: 26258
String.fromCharCode
Convert a Unicode number into a character.
var regex = new RegExp("^[a-zA-Z0-9 ,.!?]+$");
Its a regular expression to check if the entered key is from alphabets or numbers or full stop or a comma or a !.
String.fromCharCode(e.charCode ? e.which : e.charCode);
this return either the key code of pressed key or the char code.
Ex: var res = String.fromCharCode(65);
return A
if (regex.test(str)) {
to check whether the key pressed is accepted or not.
Upvotes: 1