TNK
TNK

Reputation: 4323

Allow text box only uppercase, lowercase letters and space in jquery

I want to make a text box allow only lowercase(a-z), uppercase(A-Z) letters and space using jQuery.

When I searching it on here I found this code, but it allow only lowercase letters.

<input name="lorem" class="alphaonly">
<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){ 
    var node = $(this);
    node.val(node.val().replace(/[^a-z]/g,'') ); }
);
</script>

So I tried it using /[^a-zA-Z ]/g But I couldn't figure it out.

Hope somebody may help me out.

Thank you.

Upvotes: 1

Views: 4907

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use the i flag on the Regex to make it case-insensitive and \s to allow spaces. Finally you can also use a function to amend the current value, to save having to cache the selector. Try this:

$('.alphaonly').bind('keyup blur', function() { 
    $(this).val(function(i, val) {
        return val.replace(/[^a-z\s]/gi,''); 
    });
});

Example fiddle

Depending on your jQuery version you should also change bind() to on().

Upvotes: 1

Franz&#233; Jr.
Franz&#233; Jr.

Reputation: 1194

var pattern = /^[a-z]+$/;

That pattern will match one or more lower-case alphabetic characters, and no other characters.

Upvotes: 0

Related Questions