Reputation: 63
I need a jquery function that allows only alphabets and spaces on textbox and prevent users to type numbers and symbols.
My code below is working but the symbols are allowed in textbox.
HTML:
<input id="inputTextBox" type="text" />
jQuery:
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
//if digits or not a space then don't let keypress work.
if((inputValue > 47 && inputValue < 58) && (inputValue != 32)){
event.preventDefault();
}
});
});
Upvotes: 0
Views: 3196
Reputation: 43479
Just use regex /[^a-zA-Z\s]/
to match anything, that is not letter or space.
$(document).ready(function() {
$(document).on("input change paste", "input", function() {
var newVal = $(this).val().replace(/[^a-zA-Z\s]/g, '');
$(this).val(newVal);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" placeholder="Letters and spaces only!" />
Upvotes: 3
Reputation: 11
This is code to allow only numeric values, it does't allow characters (alphabetic) and spaces:
$('input').keypress(function( e ) {
if((e.which === 32) || (e.which > 64 && e.which < 91) || (e.which > 96 && e.which < 123))
return false;
}); code here
Upvotes: 1
Reputation: 51
Try using regular expressions. This one only allows spaces and alphabet.
it also displays a span error. you need to make that with your preferred message. if you uncomment the 7th line.
<script type="text/javascript">
$(function () {
$("#inputTextBox").keypress(function(event){
var isValid = false;
var regex = /^[a-zA-Z ]*$/;
isValid = regex.test($("[id=inputTextBox]").val());
// $("#spnError").css("display", !isValid ? "block" : "none");
return isValid;
});
});
</script>
Upvotes: 0
Reputation: 781068
Check for the characters you want to allow:
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
//if digits or not a space then don't let keypress work.
if((inputValue > 64 && inputValue < 91) // uppercase
|| (inputValue > 96 && inputValue < 123) // lowercase
|| inputValue == 32) { // space
return;
}
event.preventDefault();
});
Upvotes: 0