Alpha-only character validation in JavaScript - javascript

I am working on this code in which it checks validation on numeric characters. In the same way, I want validation on alpha-only characters. I have tried many symbols but failed to succeed.
if (/\D/.test(x))
{
alert("Please only enter numeric characters (Allowed input:0-9)")
return false;
}
What changes are required in this code for alpha-only validation.

Using .test()
If you want to keep with the .test() method, I believe that the below would work for you.
Identify if the input is numeric.
if (/^[a-zA-Z]+$/.test(x))
{
alert("Please only enter numeric characters (Allowed input:0-9)")
return false;
}
Identify if the input contains a-z/A-Z
if (!/^[a-zA-Z]+$/.test(x))
{
alert("Please only enter letters (Allowed input: a-z, A-Z)")
return false;
}
Fiddle
Not Using .test()
You can also set up functions that look for the value during the onkeypress event
Allow only numerical characters to be entered in select fields || onkeypress="return isNumberKey(event)"
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode > 31 && (charCode < 48 || charCode > 57)){return false;}
return true;
}
Allow only alpha characters to be entered in select fields || onkeypress="return isAlphaKey(event)"
function isAlphaKey(evt)
{
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));
if(charCode > 32 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)){return false;}
return true;
}

Related

jquery - allow only negative, positive or decimal number validation in field

I use this code for positive validation of numbers and decimal. Now I would like to allow also negative numbers and decimals but it is not working. Any idea please?
$('.number_only').keypress(function(e){
return isNumbers(e, this);
});
function isNumbers(evt, element)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57)
)
return false;
return true;
}
I found this but no idea how to implement it jquery - allow only negative, positive or decimal number validation
You can use regex instead to solve your problem, change your method to something like this:
function isNumbers(evt, element)
{
var elementValue = $(element).val();
var regex = /^(\+|-)?(\d*\.?\d*)$/;
if (regex.test(elementValue + String.fromCharCode(evt.charCode))) {
return true;
}
return false;
}

Jquery to allow alphanumeric characters and non-text key presses

I have one text box in which, user should enter only alphanumeric characters and non-text key presses should be allowed like backspace, arrow keys, etc . Also, it should also work on all major browsers (like Mozilla Firefox).
I have tried few examples which allowed to me enter only alphanumeric characters but backspace don't work with this below example in Mozilla Firefox.
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
You can add [\b] to match and allow backspace.
Code:
var regex = new RegExp("^[a-zA-Z0-9\b]+$");
Demo: http://jsfiddle.net/M3bvN/
UPDATE
Instead of extend your regex you can check if the pressed key is in a list of allowed keys (arrows, home, del, canc) and if so skip the validation.
This not prevent the user to copy/paste not allowed characters. so perform the validation control in the blur event too (and always on server side).
Code:
var keyCode = event.keyCode || event.which
// Don't validate the input if below arrow, delete and backspace keys were pressed
if (keyCode == 8 || (keyCode >= 35 && keyCode <= 40)) { // Left / Up / Right / Down Arrow, Backspace, Delete keys
return;
}
Demo: http://jsfiddle.net/M3bvN/3/
I was working on this for a bit, and this is what I came up with:
var input = $('input[name="whatever"]');
input.bind('keypress', function(e)
{
if ((e.which < 65 || e.which > 122) && (e.which < 48 || e.which > 57))
{
e.preventDefault();
}
});
It only allows numbers and letters, both upper- and lower-case. Note that it also disallows the space bar (that's what was needed for my application).
function lettersOnly(evt) {
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
((evt.which) ? evt.which : 0));
if (charCode == 8 || charCode == 46 || charCode == 37 || charCode == 39) {
return true;
} else if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
// alert("Enter letters only.");
return false;
}
return true;
}
$('.alphanumeric').bind('keypress', function (e) {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
return ret;
});
This code will Firefox also

JavaScript - How to enable arrow key in Firefox browser while validating input fields against special characters

I'm validating my input field using key code to enter (a-z, A-Z, _). The javascript code looks something like this:
function checkForSpecialCharacters(event) {
var keycode;
keycode = event.keyCode ? event.keyCode : event.which;
if ((keycode >= 48 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode == 9)
|| (keycode == 95)||(keycode == 8) || (keycode >= 97 && keycode <= 122)) {
return true;
}
else {
return false;
}
return true;
}
This works pretty fine in Chrome, IEs, but in firefox it prevents arrow key also.
I've gone through What are the ascii values of up down left right?. But In my case I need to prevent to enter all the special characters in input field.
The give solution in the above link does not fulfill my requirement.
Kindly reply with your positive response.
Thanks.
Got the solution of this problem. Just use event.which. Here which is a property of the event object. It contains the key code of the key which was pressed to trigger the event (eg: keydown, keyup etc.).
So just get the value fo the key pressed using event.which and check in if condition.
In my case in Firefox browser I was getting 0 for arrow keys. so I just added on more or condition like:
if ((keycode >= 48 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode == 9)
|| (event.which == 0) || (keycode == 95)||(keycode == 8) || (keycode >= 97 && keycode <= 122)) {
return true;}
Hope it will help other pal.
Thanks

Allow only numbers or decimal point in form field

I've limited the input field to only numbers through js but am not sure how to also allow decimals...
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Thank you in advance!
Answer:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
return true;
}
Adding the charCode 46 worked perfectly (keypress value). 190 and 110 did nothing.
Thanks for your help all!
Codes depend on which event you're listening to, an easy way to find what you want is by using the JavaScript Event KeyCode Test Page here with test input, e.g. for a full stop (the . left of right shift) you have
onKeyDown onKeyPress onKeyUp
event.keyCode 190 46 190
event.charCode 0 46 0
event.which 190 46 190
and for the . on the numeric pad it is
onKeyDown onKeyPress onKeyUp
event.keyCode 110 46 110
event.charCode 0 46 0
event.which 110 46 110
As you can see, it is most uniform to check with onKeyPress with charCode which is it's unicode number; String.fromCharCode(46); // ".".
There is a full list on the MDN page for KeyboardEvent where it is also stated
Note: Web developers shouldn't use keycode attribute of printable keys in keydown and keyup event handlers. As described above, keycode is not usable for checking character which will be inputted especially when Shift key or AltGr key is pressed. When web developers implement shortcut key handler, keypress event is better event for that purpose on Gecko at least. See Gecko Keypress Event for the detail.
You can observe the strange effects of using AltGr or Shift on keyCode with the key of choice in the test page I linked to as well.
With HTML5, the input element got a new attribute: pattern. You can specify a regular expression that is validated by the browser before submitting the form.
<input type="text" pattern="([0-9]+\.)?[0-9]+" />
It is not widely supported yet, though.
The pattern attribute is supported in Internet Explorer 10, Firefox, Opera, and Chrome.
(w3schools)
Disclaimer: the expression is weak, go build a better one :)
Assuming you're using on key down or up:
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || (charCode > 57 && charCode != 190 && charCode != 110)))
return false;
return true;
}
110 is decimal point, 190 is period
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Heres a fiddle with some test cases
<asp:TextBox ID="txt" onkeypress="return isDecimalKey(event,this)" runat="server">
function isDecimalKey(evt,obj)
{
var charCode = (evt.which) ? evt.which : event.keyCode
var value = obj.value;
var dotcontains = value.indexOf(".") != -1;
if (dotcontains)
if (charCode == 46) return false;
if (charCode == 46) return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
}
In MVC
#Html.TextBoxFor(m => m.fieldName, new { htmlAttributes = new { #class = "form-
control forDecimal" }})
$(document).on("keypress", ".forDecimal", function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
var value = $(this).val();
var dotcontains = value.indexOf(".") != -1;
if (dotcontains)
if (charCode == 46) return false;
if (charCode == 46) return true;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
});

How to prevent users from entering invalid characters inside an input field

Given a text input field. How can I prevent users from entering spaces, and other other than letters numbers or dashes (-).
Alphanumerics only - "The alphanumeric character set consists of the numbers 0 to 9 and letters A to Z. In the perl programming language, the underscore character ( _ ) is also considered to be a member of the alphanumeric set of characters"
This is for a field where users can pick a custom url. I would like to prevent users from entering invalid characters.
Ideas? Thanks
You can do this using the jQuery keyup(..) method. You will want to check that the event.keyCode is something valid. If it is not valid, you can prevent the event with preventDefault().
Remember to validate the data sent to the server because anything you do in javascript can be subverted.
Here is a library to do it for you: http://www.itgroup.com.ph/alphanumeric/
DEMO - JS Fiddle Link
Sorry for the late response. Though my answer is late. I have modified few changes to the answer and here it goes.
Validation Required
Restrict Digits entering on initial
Restrict Spaces, special characters but allow backspace and delete
Enable Alpha Numeric Characters
<input name="pac_code" id="input_8_6" type="text" value="" class="form-control medium pacerror pacvalid" data-rule-maxlength="9" data-rule-minlength="9" maxlength="9" minlength="9" placeholder="Porting authorisation code (PAC) *" data-rule-required="true"
autocomplete="off" size="9">
<label for="input_8_6" style="color: #ff0000;font-weight: 300;font-size: 12px;margin-bottom: 1%;">Example: ABC123456</label><br />
<label class="PAC_error error" style="display:none;">Invalid PAC Format</label>
</div>
JQuery
jQuery(document).ready(function() {
$('#input_8_6').bind('keypress', function(event) {
var regex = new RegExp("^[a-zA-Z0-9\b]+$");
var regchar = new RegExp("^[a-zA-Z\b]+$");
var regnum = new RegExp("^[0-9\b]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
var pacvalue = $(this).val().length;
if (!regex.test(key)) {
event.preventDefault();
return false;
} else if (pacvalue <= 2) {
for (i = 0; i <= 2; i++) {
if (!regchar.test(key)) {
event.preventDefault();
return false;
}
}
} else if (pacvalue >= 3) {
for (j = 4; j <= 9; j++) {
if (!regnum.test(key)) {
event.preventDefault();
return false;
}
}
} else {
return true;
}
});
});
There are plenty of Javascript validation libraries out there. A quick Google search for 'javascript validation' produced the JQuery Validation plugin plugin as the first hit, so that's probably a good place to start.
As #Chris Cooper said, make sure that you also do server-side validation, because it's pretty trivial for a user to turn off javascript and avoid your client-side validation rules.
Though my answer is very late, but this may help for further readers/techie's.
Who wants to implement a textbox to accepts with below condition.
should accept Alphabets.
should accept Numbers.
should not accept any special characters.
Below is the code.
$("input[name='txtExample'] ").focus(function (e) {
if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
event.preventDefault();
}
}).keyup(function (e) {
if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
event.preventDefault();
}
}).keypress(function (e) {
if (!(e.which != 8 && e.which != 0 && ((e.which >= 48 && e.which <= 57) || (e.which >= 65 && e.which <= 90) || (e.which >= 97 && e.which <= 122) ))) {
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtExample"/>
added with example.

Categories