admin管理员组

文章数量:1221373

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)

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)

Share Improve this question edited Nov 28, 2013 at 12:35 kk1076 asked Nov 28, 2013 at 10:31 kk1076kk1076 1,74814 gold badges45 silver badges77 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 11

try following regex

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

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

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

Here's a link

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

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

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

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

本文标签: javascriptValidation to allow space character only when followed by an alphabetStack Overflow