kk1076
kk1076

Reputation: 1748

Validation to allow space character only when followed by an alphabet

I am trying to validate the textbox which has to allow space character only when followed by any alphabetic character. My code fails when only a space character is inserted. What is the mistake in my code. Suggestions pls..

javascript :

function validate() {
    var firstname = document.getElementById("FirstName");
    var alpha = /^[a-zA-Z\s-, ]+$/;  
    if (firstname.value == "") {
        alert('Please enter Name');
        return false;
    }
    else if (!firstname.value.match(alpha)) {
        alert('Invalid ');       
        return false;
   }
   else 
   {
    return true;
   }
}

view:

  @Html.TextBoxFor(m => m.FirstName, new { @class = "searchbox" })    
 <button type="submit" onclick="return validate();">Submit</button>

Conditions I applied :
Eg: Arun Chawla - condition success
Eg: _ - condition fails (should not allow space character alone)

Upvotes: 2

Views: 57449

Answers (5)

Amresh Singh
Amresh Singh

Reputation: 1

if(!/^[A-Za-z\s]+$/.test(name)) {
    errors['name'] = "Enter a valid name"
}

Upvotes: 0

easwar ranga
easwar ranga

Reputation: 1

This will allow the space between every character,number and special character(@).

pattern to be followed:

['', [Validators.email,
        Validators.pattern('^[[\\\sa-z 0-9._%+-]+@[\\\sa-z0-9.-]+\\.[\\\sa-z]{2,4}]*$')]],

output:

e 2 @ 2 g . c o

Upvotes: 0

sam
sam

Reputation: 340

Here's a link

I found Akiross's answer to be the best fit for me.

([a-z] ?)+[a-z]

Upvotes: 0

andru255
andru255

Reputation: 29

May be using the "test" method like this:

/^[a-zA-Z-,](\s{0,1}[a-zA-Z-, ])*[^\s]$/.test(firstname)

Only returns true when it's valid

Upvotes: 0

Erdogan Kurtur
Erdogan Kurtur

Reputation: 3685

try following regex

 var alpha = /^[a-zA-Z-,]+(\s{0,1}[a-zA-Z-, ])*$/

First part forces an alphabetic char, and then allows space.

Upvotes: 11

Related Questions