c0d3n4m3
c0d3n4m3

Reputation: 75

jQuery Form Validation - Only allow letters - Also disallow spaces

I've been racking my brain on this one. I've not used jQuery Validate, I wrote my own validation script for an application form. Only thing is, everything in my form validates fine, except in the firstname and lastname fields, it allows spaces to be used instead of letters (which I don't want) and I only want it to accept letters, no spaces or numbers.

Only thing is, I can't get it to do that. It understands that if nothing is inserted into the first and last name fields, then it won't validate and you cannot continue to the second page of the form, unless there is actually something in the two fields.

Sadly, you can just put a space in both in the fields, and it will accept that.. not good.. Also, you can use numbers, also not good.

I only want letters to be allowed in both the fields, and have tried a few things, but to no avail.

Here is the code that does the validating for those two fields:

if(firstname!="" && firstname.match(/^[a-zA-Z_]$/))  {
            $("#FirstName").parent("label").css('color','#444');
        }else {
            $(".errors").append("<br/>Please enter your First Name").show();
            $("#FirstName").parent("label").css('color','#FF0000');
        }
        if(surname!="" && surname.match(/^[a-zA-Z_]$/))  {
            $("#Surname").parent("label").css('color','#444');
        }else {
            $(".errors").append("<br/>Please enter your Last Name").show();
            $("#Surname").parent("label").css('color','#FF0000');
        }

Upvotes: 0

Views: 2303

Answers (1)

Rob Schmuecker
Rob Schmuecker

Reputation: 8954

You can check this way.

if(firstname!="" && (firstname.match(/^[a-zA-Z]$/) !== null))  {
            $("#FirstName").parent("label").css('color','#444');
        }else {
            $(".errors").append("<br/>Please enter your First Name").show();
            $("#FirstName").parent("label").css('color','#FF0000');
        }
        if(surname!="" && (surname.match(/^[a-zA-Z]$/) !== null))  {
            $("#Surname").parent("label").css('color','#444');
        }else {
            $(".errors").append("<br/>Please enter your Last Name").show();
            $("#Surname").parent("label").css('color','#FF0000');
        }

However I would recommend allowing spaces in general in a surname/last name as various people have surnames such as "Van Dam" etc.

Edit

I removed the underscores from the Regex to disallow underscores as you intended for only letters.

Upvotes: 1

Related Questions