Reputation: 483
I made a regular expression that only accepts letters. I'm not really good in regex, thats why I don't know how to include spaces in my regex.
My HTML:
<input id="input" />
My js / jQuery code:
$('#input').on('keyup', function() {
var RegExpression = /^[a-zA-Z]*$/;
if (RegExpression.test($('#input').val())) {
}
else {
$('#input').val("");
}
});
Upvotes: 44
Views: 168723
Reputation: 8476
use this expression
var RegExpression = /^[a-zA-Z\s]*$/;
Update: 27-April-2023
function validate(){
const regEx1 = /[^a-zA-Z\s]+/;
input.value = input.value.replace(regEx1, '');
}
<input id="input" type="text" onkeyup="return validate();">
Upvotes: 100
Reputation: 720
regex expression:
var reg_name_lastname = /^[a-zA-Z\s]*$/;
Validation to the user_name input field
if(!reg_name_lastname.test($('#user_name').val())){ //
alert("Correct your First Name: only letters and spaces.");
valid = false;
}
Upvotes: 0
Reputation: 1
Allowed only characters & spaces. Ex : Jayant Lonari
if (!/^[a-zA-Z\s]+$/.test(NAME)) {
//Throw Error
}
Upvotes: -1
Reputation: 34117
Try this demo please: http://jsfiddle.net/sgpw2/
Thanks Jan for spaces \s
rest there is some good detail in this link:
http://www.jquery4u.com/syntax/jquery-basic-regex-selector-examples/#.UHKS5UIihlI
Hope it fits your need :)
code
$(function() {
$("#field").bind("keyup", function(event) {
var regex = /^[a-zA-Z\s]+$/;
if (regex.test($("#field").val())) {
$('.validation').html('valid');
} else {
$('.validation').html("FAIL regex");
}
});
});
Upvotes: 4
Reputation: 123428
$('#input').on('keyup', function() {
var RegExpression = /^[a-zA-Z\s]*$/;
...
});
\s
will allow the space
Upvotes: 10