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)
5 Answers
Reset to default 11try 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
版权声明:本文标题:javascript - Validation to allow space character only when followed by an alphabet - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739344078a2159074.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论