Reputation: 4721
I want a javascript validation on a textbox which can accept.
a. Characters
b. Characters with Numbers
It should not accept only numbers
For example i want something like:-
Abc123, A7 organisation.
but I dont want like;-
333333 , 2222222.
Also, special characters are also not allowed
I tried like below js function but it is not working
function NumersWithCharValidation() {
var textBoxvalue = document.getElementById('txtNameOfFirm').value;
alert(textBoxvalue);
if (textBoxvalue.match("/^(?![0-9]*$)[a-zA-Z0-9]+$/")) {
alert('Good to go');
}
else {
alert('Only Numbers are not allowed');
}
}
<input id="txtNameOfFirm" runat="server" onkeypress="return NumersWithCharValidation();" maxlength="200" type="text" width="65%" />
kindly suggest what is wrong
Upvotes: 1
Views: 186
Reputation: 29
This will not allow the user to type any further
jQuery("#txtNameOfFirm").keypress(function (event, ui)
{ return NumersWithCharValidation(event) });
and
function NumersWithCharValidation(evt) {
if (jQuery("#txtNameOfFirm").val().match(/^[0-9]+$/) == null)
{ return true; } else { return false; }
}
Upvotes: 0
Reputation: 68393
change the method to
function NumersWithCharValidation(thisObj) {
var textBoxvalue = thisObj.value;
if ( textBoxvalue.length > 0 && isNaN( textBoxvalue ) && !textBoxvalue.match( /\W/ ) )
{
alert('Good to go');
}
else
{
alert('Only Numbers are not allowed. Special characters are also not allowed' );
}
}
<input id="txtNameOfFirm" runat="server" onkeypress="return NumersWithCharValidation(this);" maxlength="200" type="text" width="65%" />
isNaN( "textBoxvalue" )
will check if the value is a pure number
textBoxvalue.match( /\W/ )
checks if there is any special character in the value
Upvotes: 2
Reputation: 14688
How about a regex like this? Positive lookahead for letters, it works for your example inputs.
if (textBoxvalue.match("/^(?=[a-zA-Z]+)[\w\s,]*$/")) {
alert('Good to go');
} else {
alert('Only Numbers are not allowed');
}
Upvotes: 0