Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for names validation allow only letters and spaces

I'm trying to validate using jQuery Validator if input only contains spaces, and allow space only if there's a letter inside it.

Note that it should also display error if name contains numbers. Allow only the space if it starts with a letter.

This is what I have so far that only allows letters and spaces:

jQuery.validator.addMethod("letterswithspace", function(value, element) {
    return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "letters only");

Also tried this one but it trims the string and can't add a space between names:

first_name : {
    letterswithspace : true,
     required: {
         depends:function(){
             $(this).val($.trim($(this).val()));
             return true;
         }
     }
 }
like image 469
claudios Avatar asked Feb 01 '17 08:02

claudios


People also ask

How do I allow only special characters in regex?

You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.

Does \w include space?

A more accurate wording for \W is any Non-Alphanumeric character. \s is for Any Whitespace. Show activity on this post. \W means "non-word characters", the inverse of \w , so it will match spaces as well.

How do I match a character except space in regex?

You can match a space character with just the space character; [^ ] matches anything but a space character.


Video Answer


1 Answers

To match the terms:

  • Expression can start only with a letter
  • Expression can contain letters or spaces

You need to use this regex expression:

/^[a-z][a-z\s]*$/

So in your js it should be:

jQuery.validator.addMethod("letterswithspace", function(value, element) {
    return this.optional(element) || /^[a-z][a-z\s]*$/i.test(value);
}, "letters only");

Explanation

  1. ^[a-z] means start with one letter
  2. [a-z\s]*$ means after accept zero or more letters or spaces

Valid sentence

If you want a valid sentence structure:

  • Expression can start or end only with a letter
  • Expression cannot contain consecutive spaces

use:

/^([a-z]+\s)*[a-z]+$/

By the way

  1. These regex expressions do not accept capital letters. To add capital letters support instead of a-z use a-zA-Z
like image 163
Jaqen H'ghar Avatar answered Oct 05 '22 22:10

Jaqen H'ghar