Validation on textbox using jquery for pan Number format - javascript

I have to add Pan no in my website Application but i have to use jquery for validation so that first 5 no. should be alphabet then 4 no. should be numeric and the last Questions should be alphabet.
$('#txtPANNumber').keypress(function (event) {
var key = event.which;
var esc = (key == 127 || key == 8 || key == 0 || key == 46);
//alert(key);
//var nor = $("#txtPANNumber").mask("aaaaa9999a");
var regExp = /[a-zA-z]{5}\d{4}[a-zA-Z]{1}/;
var txtpan = $(this).val();
if (txtpan.length < 10 ) {
if( txtpan.match( regExp) ){
//event.preventDefault();
}
} else { event.preventDefault(); } });
Please provide some solutions

This will do
/[a-zA-z]{5}\d{4}[a-zA-Z]{1}/
Check here
Code
$('#txtPANNumber').change(function (event) {
var regExp = /[a-zA-z]{5}\d{4}[a-zA-Z]{1}/;
var txtpan = $(this).val();
if (txtpan.length == 10 ) {
if( txtpan.match(regExp) ){
alert('PAN match found');
}
else {
alert(Not a valid PAN number);
event.preventDefault();
}
}
else {
alert('Please enter 10 digits for a valid PAN number');
event.preventDefault();
}
});

You can use below regex to validate input for PAN.
[A-Z]{5}[0-9]{4}[A-Z]{1}
Function for JS :
function validatePAN(pan){
var regex = /[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
return regex.test(pan);
}
But don't rely only on JS validation, as JS validation can easily disabled from client side. Put a check on server side as well for inputs.
Also you need to change your if condition to something like below :
if(length == 10)

Related

Multiple condition for phone number field in javascript

I have below code:
$('.mobileNumber').keyup(function () {
var mobile = $(this).val();
var numericExpression = /^[0-9]+$/;
if (mobile.length == 0 || mobile.length < 10 || !mobile.match(numericExpression)) {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','block');
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
}
});
what i'm trying to do is whenever my mobileNumber fields blank(ie. o length),less than 10 length and it should follow numbers only. if yes, then error message i.e. .jp-error-msg-kstm will appear else not.
for example, if i entered 1234567890 then it should not show me the error whereas if erase the value and make the field as 0 length or less than 10 then it should shoe the error span div.
Simply use .length.
if (mobile.length < 10 || !mobile.match(numericExpression)) {
I have used
mobile.length == 0
in the first if condition only.
So the code become
$('.mobileNumber').keyup(function () {
var mobile = $(this).val();
var numericExpression = /^[0-9]+$/;
if (mobile.length < 10 || !mobile.match(numericExpression)) {
if(mobile.length == 0){
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','block');
}
} else {
$(this).parent().parent().parent().find('.jp-error-msg-kstm').css('display','none');
}
});

How do i restrict some specific special character from input? [duplicate]

How do I block special characters from being typed into an input field with jquery?
A simple example using a regular expression which you could change to allow/disallow whatever you like.
$('input').on('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;
}
});
I was looking for an answer that restricted input to only alphanumeric characters, but still allowed for the use of control characters (e.g., backspace, delete, tab) and copy+paste. None of the provided answers that I tried satisfied all of these requirements, so I came up with the following using the input event.
$('input').on('input', function() {
$(this).val($(this).val().replace(/[^a-z0-9]/gi, ''));
});
Edit:
As rinogo pointed out in the comments, the above code snippet forces the cursor to the end of the input when typing in the middle of the input text. I believe the code snippet below solves this problem.
$('input').on('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Short answer: prevent the 'keypress' event:
$("input").keypress(function(e){
var charCode = !e.charCode ? e.which : e.charCode;
if(/* Test for special character */ )
e.preventDefault();
})
Long answer: Use a plugin like jquery.alphanum
There are several things to consider when picking a solution:
Pasted text
Control characters like backspace or F5 may be prevented by the above code.
é, í, ä etc
Arabic or Chinese...
Cross Browser compatibility
I think this area is complex enough to warrant using a 3rd party plugin. I tried out several of the available plugins but found some problems with each of them so I went ahead and wrote jquery.alphanum. The code looks like this:
$("input").alphanum();
Or for more fine-grained control, add some settings:
$("#username").alphanum({
allow : "€$£",
disallow : "xyz",
allowUpper : false
});
Hope it helps.
Use simple onkeypress event inline.
<input type="text" name="count" onkeypress="return /[0-9a-zA-Z]/i.test(event.key)">
Use HTML5's pattern input attribute!
<input type="text" pattern="^[a-zA-Z0-9]+$" />
Use regex to allow/disallow anything. Also, for a slightly more robust version than the accepted answer, allowing characters that don't have a key value associated with them (backspace, tab, arrow keys, delete, etc.) can be done by first passing through the keypress event and check the key based on keycode instead of value.
$('#input').bind('keydown', function (event) {
switch (event.keyCode) {
case 8: // Backspace
case 9: // Tab
case 13: // Enter
case 37: // Left
case 38: // Up
case 39: // Right
case 40: // Down
break;
default:
var regex = new RegExp("^[a-zA-Z0-9.,/ $#()]+$");
var key = event.key;
if (!regex.test(key)) {
event.preventDefault();
return false;
}
break;
}
});
Your textbox:
<input type="text" id="name">
Your javascript:
$("#name").keypress(function(event) {
var character = String.fromCharCode(event.keyCode);
return isValid(character);
});
function isValid(str) {
return !/[~`!##$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Take a look at the jQuery alphanumeric plugin. https://github.com/KevinSheedy/jquery.alphanum
//All of these are from their demo page
//only numbers and alpha characters
$('.sample1').alphanumeric();
//only numeric
$('.sample4').numeric();
//only numeric and the .
$('.sample5').numeric({allow:"."});
//all alphanumeric except the . 1 and a
$('.sample6').alphanumeric({ichars:'.1a'});
this is an example that prevent the user from typing the character "a"
$(function() {
$('input:text').keydown(function(e) {
if(e.keyCode==65)
return false;
});
});
key codes refrence here:
http://www.expandinghead.net/keycode.html
I use this code modifying others that I saw. Only grand to the user write if the key pressed or pasted text pass the pattern test (match) (this example is a text input that only allows 8 digits)
$("input").on("keypress paste", function(e){
var c = this.selectionStart, v = $(this).val();
if (e.type == "keypress")
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode)
else
var key = e.originalEvent.clipboardData.getData('Text')
var val = v.substr(0, c) + key + v.substr(c, v.length)
if (!val.match(/\d{0,8}/) || val.match(/\d{0,8}/).toString() != val) {
e.preventDefault()
return false
}
})
$(function(){
$('input').keyup(function(){
var input_val = $(this).val();
var inputRGEX = /^[a-zA-Z0-9]*$/;
var inputResult = inputRGEX.test(input_val);
if(!(inputResult))
{
this.value = this.value.replace(/[^a-z0-9\s]/gi, '');
}
});
});
Write some javascript code on onkeypress event of textbox.
as per requirement allow and restrict character in your textbox
function isNumberKeyWithStar(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 42)
return false;
return true;
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
function isNumberKeyForAmount(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
return true;
}
To replace special characters, space and convert to lower case
$(document).ready(function (){
$(document).on("keyup", "#Id", function () {
$("#Id").val($("#Id").val().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '').toLowerCase());
});
});
Yes you can do by using jQuery as:
<script>
$(document).ready(function()
{
$("#username").blur(function()
{
//remove all the class add the messagebox classes and start fading
$("#msgbox").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
//check the username exists or not from ajax
$.post("user_availability.php",{ user_name:$(this).val() } ,function(data)
{
if(data=='empty') // if username is empty
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Empty user id is not allowed').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(data=='invalid') // if special characters used in username
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('Sorry, only letters (a-z), numbers (0-9), and periods (.) are allowed.').addClass('messageboxerror').fadeTo(900,1);
});
}
else if(data=='no') // if username not avaiable
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('User id already exists').addClass('messageboxerror').fadeTo(900,1);
});
}
else
{
$("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
{
//add message and change the class of the box and start fading
$(this).html('User id available to register').addClass('messageboxok').fadeTo(900,1);
});
}
});
});
});
</script>
<input type="text" id="username" name="username"/><span id="msgbox" style="display:none"></span>
and script for your user_availability.php will be:
<?php
include'includes/config.php';
//value got from the get method
$user_name = trim($_POST['user_name']);
if($user_name == ''){
echo "empty";
}elseif(preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $user_name)){
echo "invalid";
}else{
$select = mysql_query("SELECT user_id FROM staff");
$i=0;
//this varible contains the array of existing users
while($fetch = mysql_fetch_array($select)){
$existing_users[$i] = $fetch['user_id'];
$i++;
}
//checking weather user exists or not in $existing_users array
if (in_array($user_name, $existing_users))
{
//user name is not availble
echo "no";
}
else
{
//user name is available
echo "yes";
}
}
?>
I tried to add for / and \ but not succeeded.
You can also do it by using javascript & code will be:
<!-- Check special characters in username start -->
<script language="javascript" type="text/javascript">
function check(e) {
var keynum
var keychar
var numcheck
// For Internet Explorer
if (window.event) {
keynum = e.keyCode;
}
// For Netscape/Firefox/Opera
else if (e.which) {
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
//List of special characters you want to restrict
if (keychar == "'" || keychar == "`" || keychar =="!" || keychar =="#" || keychar =="#" || keychar =="$" || keychar =="%" || keychar =="^" || keychar =="&" || keychar =="*" || keychar =="(" || keychar ==")" || keychar =="-" || keychar =="_" || keychar =="+" || keychar =="=" || keychar =="/" || keychar =="~" || keychar =="<" || keychar ==">" || keychar =="," || keychar ==";" || keychar ==":" || keychar =="|" || keychar =="?" || keychar =="{" || keychar =="}" || keychar =="[" || keychar =="]" || keychar =="¬" || keychar =="£" || keychar =='"' || keychar =="\\") {
return false;
} else {
return true;
}
}
</script>
<!-- Check special characters in username end -->
<!-- in your form -->
User id : <input type="text" id="txtname" name="txtname" onkeypress="return check(event)"/>
just the numbers:
$('input.time').keydown(function(e) { if(e.keyCode>=48 &&
e.keyCode<=57) {
return true; } else {
return false; } });
or for time including ":"
$('input.time').keydown(function(e) { if(e.keyCode>=48 &&
e.keyCode<=58) {
return true; } else {
return false; } });
also including delete and backspace:
$('input.time').keydown(function(e) { if((e.keyCode>=46 &&
e.keyCode<=58) || e.keyCode==8) { return true; } else {
return false; } });
unfortuneatly not getting it to work on a iMAC
Wanted to comment on Alex's comment to Dale's answer. Not possible (first need how much "rep"? That wont happen very soon.. strange system.)
So as an answer:
Backspace can be added by adding \b to the regex definition like this: [a-zA-Z0-9\b].
Or you simply allow the whole Latin range, including more or less anything "non exotic" characters (also control chars like backspace): ^[\u0000-\u024F\u20AC]+$
Only real unicode char outside latin there is the euro sign (20ac), add whatever you may need else.
To also handle input entered via copy&paste, simply also bind to the "change" event and check the input there too - deleting it or striping it / giving an error message like "not supported characters"..
if (!regex.test($j(this).val())) {
alert('your input contained not supported characters');
$j(this).val('');
return false;
}
Restrict specials characters on keypress. Here's a test page for key codes: http://www.asquare.net/javascript/tests/KeyCode.html
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
some_element.bind("keypress", function(event) {
// prevent if in array
if($.inArray(event.which,specialChars) != -1) {
event.preventDefault();
}
});
In Angular, I needed a proper currency format in my textfield. My solution:
var angularApp = angular.module('Application', []);
...
// new angular directive
angularApp.directive('onlyNum', function() {
return function( scope, element, attrs) {
var specialChars = [62,33,36,64,35,37,94,38,42,40,41];
// prevent these special characters
element.bind("keypress", function(event) {
if($.inArray(event.which,specialChars) != -1) {
prevent( scope, event, attrs)
}
});
var allowableKeys = [8,9,37,39,46,48,49,50,51,52,53,54,55,56
,57,96,97,98,99,100,101,102,103,104,105,110,190];
element.bind("keydown", function(event) {
if($.inArray(event.which,allowableKeys) == -1) {
prevent( scope, event, attrs)
}
});
};
})
// scope.$apply makes angular aware of your changes
function prevent( scope, event, attrs) {
scope.$apply(function(){
scope.$eval(attrs.onlyNum);
event.preventDefault();
});
event.preventDefault();
}
In the html add the directive
<input only-num type="text" maxlength="10" id="amount" placeholder="$XXXX.XX"
autocomplete="off" ng-model="vm.amount" ng-change="vm.updateRequest()">
and in the corresponding angular controller I only allow there to be only 1 period, convert text to number and add number rounding on 'blur'
...
this.updateRequest = function() {
amount = $scope.amount;
if (amount != undefined) {
document.getElementById('spcf').onkeypress = function (e) {
// only allow one period in currency
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
// Remove "." When Last Character and round the number on blur
$("#amount").on("blur", function() {
if (this.value.charAt(this.value.length-1) == ".") {
this.value.replace(".","");
$("#amount").val(this.value);
}
var num = parseFloat(this.value);
// check for 'NaN' if its safe continue
if (!isNaN(num)) {
var num = (Math.round(parseFloat(this.value) * 100) / 100).toFixed(2);
$("#amount").val(num);
}
});
this.data.amountRequested = Math.round(parseFloat(amount) * 100) / 100;
}
...
You don't need jQuery for this action
You can achieve this using plain JavaScript, You can put this in the onKeyUp event.
Restrict - Special Characters
e.target.value = e.target.value.replace(/[^\w]|_/g, '').toLowerCase()
Accept - Number only
e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()
Accept - Small Alphabet only
e.target.value = e.target.value.replace(/[^0-9]/g, '').toLowerCase()
I could write for some more scenarios but I have to maintain the specific answer.
Note It will work with jquery, react, angular, and so on.
$(this).val($(this).val().replace(/[^0-9\.]/g,''));
if( $(this).val().indexOf('.') == 0){
$(this).val("");
}
//this is the simplest way
indexof is used to validate if the input started with "."
[User below code to restrict special character also
$(h.txtAmount).keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});]
Allow only numbers in TextBox (Restrict Alphabets and Special Characters)
/*code: 48-57 Numbers
8 - Backspace,
35 - home key, 36 - End key
37-40: Arrow keys, 46 - Delete key*/
function restrictAlphabets(e){
var x=e.which||e.keycode;
if((x>=48 && x<=57) || x==8 ||
(x>=35 && x<=40)|| x==46)
return true;
else
return false;
}
/**
* Forbids special characters and decimals
* Allows numbers only
* */
const numbersOnly = (evt) => {
let charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode === 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
let inputResult = /^[0-9]*$/.test(evt.target.value);
if (!inputResult) {
evt.target.value = evt.target.value.replace(/[^a-z0-9\s]/gi, '');
}
return true;
}
In HTML:
<input type="text" (keypress)="omitSpecialChar($event)"/>
In JS:
omitSpecialChar(event) {
const keyPressed = String.fromCharCode(event.keyCode);
const verifyKeyPressed = /^[a-zA-Z\' \u00C0-\u00FF]*$/.test(keyPressed);
return verifyKeyPressed === true;
}
In this example it is possible to type accents.
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
if (!(checkEmpty($("#Description").val()))) {
$("#Description").val("");
} //1Apr2022 code end
});
$('#Description').on('change', function() {
if (!(checkEmpty($("#Description").val()))) {
$("#Description").val("");
} //1Apr2022 code end
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}
A more enhanced form would be
$('input[type=text]').on('input', function() {
var c = this.selectionStart,
r = /[^a-z ]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
Because it will allow you to enter space as well and it will only target the input fields with type text and wont bother the other input fields like email, password etc as normally we need special characters in email and password field

HTML5 restricting input characters

Is it possible to restrict the input of certain characters in HTML5/JavaScript? For example, could I have an input textbox on the screen and if the user tries to type a letter in it, it wouldn't show up in the box because I've restricted it to only numbers?
I know you can use a pattern which will be checked on submit, but I want the "bad" characters to just never be entered at all.
The input textbox
<input type="text" onKeyDown="myFunction()" value="" />
JavaScript
function myFunction() {
var e = event || window.event; // get event object
var key = e.keyCode || e.which; // get key cross-browser
if (key < 48 || key > 57) { //if it is not a number ascii code
//Prevent default action, which is inserting character
if (e.preventDefault) e.preventDefault(); //normal browsers
e.returnValue = false; //IE
}
}
Use html5 pattern attribute for inputs:
<input type="text" pattern="\d*" title="Only digits" />
OR
Use html5 number type for input :
<input type="number" />
To slightly improve off of jonhopkins excellent answer, I added backspace and delete key acceptance like so:
function inputValidate(){
var e = event || window.event;
var key = e.keyCode || e.which;
if (((key>=48)&&(key<=57))||(key==8)||(key == 46)) { //allow backspace //and delete
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
}
}
For Restricting Characters symbols like '-' and ','
<input type="text" pattern="[^-,]+">
for restricting numbers
<input type="text" pattern="[^0-9]+">
for restricting letters of the alphabet
<input type="text" pattern="[^a-zA-Z]+">
KeyboardEvent.keyCode is deprecated, so here's a solution using the HMLElement.input event. This solution uses a simple regex, and handles copy-paste nicely as well by just removing the offending elements from any input.
My regex: /[^\w\d]/gi
Matches anything not (^) a word character (\w: a-z) or a digit (\d: 0-9).
g modifier makes regex global (don't return after first match)
i modifier makes regex case insensitive
With this regex, special characters and spaces won't be allowed. If you wanted to add more, you'd just have to add allowed characters to the regex list.
function filterField(e) {
let t = e.target;
let badValues = /[^\w\d]/gi;
t.value = t.value.replace(badValues, '');
}
let inputElement = document.getElementById('myInput');
inputElement.addEventListener('input', filterField);
<input id="myInput" type="text" style="width: 90%; padding: .5rem;" placeholder="Type or paste (almost) anything...">
//improved wbt11a function
function numberFieldStrictInput(allowcomma, allownegative) {
var e = event || window.event; // get event object
var key = e.keyCode ||`enter code here` e.which; // get key cross-browser
if(key==8 || key==46 || key == 9 || key==17 || key==91 || key==18 ||
key==116 || key==89 || key==67 || key==88 || key==35 || key==36) //back, delete tab, ctrl, win, alt, f5, paste, copy, cut, home, end
return true;
if(key == 109 && allownegative)
return true;
if(key == 190 && allowcomma)
return true;
if(key>=37 && key<=40) //arrows
return true;
if(key>=48 && key<=57) // top key
return true;
if(key>=96 && key<=105) //num key
return true;
console.log('Not allowed key pressed '+key);
if (e.preventDefault) e.preventDefault(); //normal browsers
e.returnValue = false; //IE
}
//on input put onKeyDown="numberFieldStrictInput(1,0)"
What about this (it supports special keys, like copy, paste, F5 automatically)?
function filterNumericInput() {
var e = event || window.event; // get event object
if (e.defaultPrevented) {
return;
}
const key = e.key || e.code;
if ((e.key.length <= 1) && (!(e.metaKey || e.ctrlKey || e.altKey))) {
if (!((key >= '0' && key <= '9') || (key === '.') || (key === ',') || (key === '-') || (key === ' '))) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
}
}
Limit input to letters, numbers and '.' (for React users only)
Here is my simple solution, I couldn't find a better solution for React and made my own. 3 steps.
First, create a state.
const [tagInputVal, setTagInputVal] = useState("");
Then, use the state as input value (value={tagInputVal}) and pass the event to the onChange handler.
<input id="tag-input" type="text" placeholder="Add a tag" value={tagInputVal} onChange={(e) => onChangeTagInput(e)}></input>
Then, set the value of the event inside onChange handler.
function onChangeTagInput(e) {
setTagInputVal(e.target.value.replace(/[^a-zA-Z\d.]/ig, ""));
}
var keybNumberAndAlpha = new keybEdit(' 0123456789abcdefghijklmnopqrstuvwxyz');
function keybEdit(strValid, strMsg) {
var reWork = new RegExp('[a-z]','gi'); // Regular expression\
// Properties
if(reWork.test(strValid))
this.valid = strValid.toLowerCase() + strValid.toUpperCase();
else
this.valid = strValid;
if((strMsg == null) || (typeof(strMsg) == 'undefined'))
this.message = '';
else
this.message = strMsg;
// Methods
this.getValid = keybEditGetValid;
this.getMessage = keybEditGetMessage;
function keybEditGetValid() {
return this.valid.toString();
}
function keybEditGetMessage() {
return this.message;
}
}
function editKeyBoard(ev, objForm, objKeyb) {
strWork = objKeyb.getValid();
strMsg = ''; // Error message
blnValidChar = false; // Valid character flag
var BACKSPACE = 8;
var DELETE = 46;
var TAB = 9;
var LEFT = 37 ;
var UP = 38 ;
var RIGHT = 39 ;
var DOWN = 40 ;
var END = 35 ;
var HOME = 35 ;
// Checking backspace and delete
if(ev.keyCode == BACKSPACE || ev.keyCode == DELETE || ev.keyCode == TAB
|| ev.keyCode == LEFT || ev.keyCode == UP || ev.keyCode == RIGHT || ev.keyCode == DOWN) {
blnValidChar = true;
}
if(!blnValidChar) // Part 1: Validate input
for(i=0;i < strWork.length;i++)
if(ev.which == strWork.charCodeAt(i) ) {
blnValidChar = true;
break;
}
// Part 2: Build error message
if(!blnValidChar)
{
//if(objKeyb.getMessage().toString().length != 0)
// alert('Error: ' + objKeyb.getMessage());
ev.returnValue = false; // Clear invalid character
ev.preventDefault();
objForm.focus(); // Set focus
}
}
<input type="text"name="worklistFrmDateFltr" onkeypress="editKeyBoard(event, this, keybNumberAndAlpha)" value="">
I found that onKeyDown captures Shift key, arrows, etc. To avoid having to account for this, I could filter out character input easily by subscribing to onKeyPress instead.
Since many of the answers above didn't satisfy me, I propose my solution which solves the problem of the input event being uncancelable by storing the previous value in a custom attribute, and restoring it in case the pattern is not matched:
const input = document.querySelector('#input-with-pattern')
input.addEventListener('keyup', event => {
const value = event.target.value;
if (!/^[a-zA-Z]+$/.test(value) && value !== '') { // it will allow only alphabetic
event.target.value = event.target.getAttribute('data-value');
} else {
event.target.setAttribute('data-value', value);
}
});
<input id="input-with-pattern">

Jquery keydown() with number format not work correctly on android webview

I have encountered a strange behavior on android browser / webview. I was testing an input that will automatically format to phone number format "(xxx) xxx-xxxx". But then what happened was when I tapped or press any number on androids keyboard, the first input was like this "(x" but then the cursor was in between "(" and "x". Is there a way to put the cursor after "x" value?
I tested this on iPhone and windows web browsers and it works fine. Please let me know if there are mistakes on my jquery or javascripts.
Thanks
HTML CODE:
<html>
<head>
<title>Sample Phone Number Format</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<input type="text" id="phone" />
<script type="text/javascript">
$('#phone').on('keydown', function (event) {
objval = $(this).val();
if (event.keyCode == 46 || event.keyCode == 8) {} else {
if (!((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode > 95 && event.keyCode < 106) || (objval.length > 13))) {
event.preventDefault();
} else {
if (objval.length == 0) {
$(this).val(objval + '(');
alert(objval + '(');
} else if (objval.length == 4) {
$(this).val(objval + ') ');
alert(objval + ') ');
} else if (objval.length == 9) {
$(this).val(objval + '-');
alert(objval + '-');
} else if (objval.length >= 14) {
if (event.keyCode == 9) {
return;
} else {
event.preventDefault();
}
}
}
}
});
$('#phone').on('keydown', function (event) {
var objVal = $(this).val();
if(objVal.length < 14)
{
validateCallerForm(objVal + String.fromCharCode((96 <= event.keyCode && event.keyCode <= 105)? event.keyCode-48 : event.keyCode));
}
});
//Validates proper phone format, true if valid phone number, false otherwise
function isValidPhoneNumber(elementValue) {
var numberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
return numberPattern.test(elementValue);
}
//validates entire caller form, also updates css classes for proper response
function validateCallerForm(PhoneNumber) {
if (isValidPhoneNumber(PhoneNumber)) {
alert("true");
} else {
alert("false");
}
}
</script>
</body>
</html>
Giving +50 Bounty to who'm will answer this correctly
you have to first define listener for typing and copy-paste like below (not required) :
$("#phone").keyup( function() {
maskLine(this);
});
$("#phone").change( function() {
maskLine(this);
});
Then, to manage cursor placement, you have to cache previous phone number and then, you could compare difference and update cursor position if needed.
So declare, you have to declare a global array like this :
var _cacheElementValues = new Array();
At last, you can check the function below, it applies your mask to phone number field and manage cursor placement :
function maskLine( element ) {
element = $(element);
var maskedLine = '';
var line = element.attr('value');
// check the cache of the input and abord if no change since last treatment
if (_cacheElementValues[element.attr('id')] != undefined && _cacheElementValues[element.attr('id')] == line) {
return;
}
line = line.replace(/\D/g, ''); // remove all characters != digits
line = line.substring(0, 10);
if (line != '') {
// apply mask
if (line.length <= 2 ) {
maskedLine = "(" + line;
} else if (line.length < 6) {
maskedLine = line.replace(/^([0-9]{3})([0-9]{0,3})/g, '($1) $2');
} else {
// mask : '(XXX) XXX-XXXX'
maskedLine = line.replace(/^([0-9]{3})([0-9]{3})([0-9]{0,4})/g, '($1) $2-$3');
}
}
// define cursor position at the end of the input by default
var pos = maskedLine.length;
// Change cursor placement if necessary
if (typeof element[0].selectionStart != 'undefined') {
var start = element[0].selectionStart;
var end = element[0].selectionEnd;
var insText = element[0].value.substring(start, end);
// get current cursor placement
if (insText.length == 0) {
pos = start;
} else {
pos = start + insText.length;
}
// find how many digits typing since last mask application
var previousLength = 0;
if (_cacheElementValues[element.attr('id')] != undefined) {
previousLength = _cacheElementValues[element.attr('id')].replace(/\s/g, '').length;
}
var diff = maskedLine.replace(/\s/g, '').length - previousLength;
// if sum of new typing digit is > 0 : we change cursor placement
if (diff > 0) {
pos += (diff - 1) + Math.round((diff-1)/3);
if (pos%6 == 0 && maskedLine.length >= pos+1) pos++;
}
}
// update input data & cache
element.val(maskedLine);
_cacheElementValues[element.attr('id')] = maskedLine;
// update cursor placement
element[0].selectionStart = element[0].selectionEnd = pos;
}
You can find this example on jsFiddle : http://jsfiddle.net/UE9LB/5/
I hope this little explantion can solve your problem ;)
Enjoy !
ps: i apologize for my poor english :s
I'd recommend at least starting with an existing plugin rather than going through your own isolated rounds of solving issues.
http://digitalbush.com/projects/masked-input-plugin/
https://github.com/igorescobar/jQuery-Mask-Plugin
The short answer is to set the selectionStart and selectionEnd properties of the input element. After you format the value, set these properties to this.value.length.
this.selectionStart = this.value.length;
this.selectionEnd = this.value.length;
But, where you are going to run into trouble is when the cursor is not at the end of the text. Eg, the user has manually positioned the cursor to a position within the text. To prevent the cursor from jumping to the end, you will need to detect the cursor position before you format the input, then put the cursor back in the appropriate position after formatting.
Edit: This jsFiddle may get you started, but isn't perfect yet.
I rewrite the code on my #phone keydown event and this will work on iPhone, Android, webkit browsers.
$('#phone').on('keydown', function (event) {
if (event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39) {
// ignore if BKSPCE, left arrow, or right arrow
} else {
// validate if anything else
inputval = $(this).val();
var string = inputval.replace(/[^0-9]/g, "");
var first3 = string.substring(0,3);
var next3 = string.substring(3,6);
var next4 = string.substring(6,10);
var string = ("(" + first3 + ") " + next3 + "-" + next4);
$(this).val(string);
}
});

Special character validation using JavaScript

Special characters <, >, %, '', "", $ and ^ are not allowed in a textbox. I need to put a validation check to restrict these characters on submit along with the null check.
I wrote entire validation code in a function and calling it on click of the submit button, but the function is not recognised on click.
Please help me write some JavaScript code to achieve this functionality.
A much simpler way is to use indexOf in javascript,
function isSpclChar(){
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
if(document.qfrm.q.value.indexOf(iChars) != -1) {
alert ("The box has special characters. \nThese are not allowed.\n");
return false;
}
}
function isSpclChar(){
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < document.qfrm.q.value.length; i++) {
if (iChars.indexOf(document.qfrm.q.value.charAt(i)) != -1) {
alert ("The box has special characters. \nThese are not allowed.\n");
return false;
}
}
}
Try this:
$('#text').keypress(function (e) {
validationForSpecialchar(e);
});
function validationForSpecialchar(e){
var regex = new RegExp("^[a-zA-Z0-9-]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter something here : <input id="text">
Try something like
<form ... onsubmit="function()">
In function you can get text from your textarea or what you are using. If data is valid function () should return true. Otherwise form wouldn't be submitted.
function alphanumeric_only(event)
{
var keycode;
keycode=event.keyCode?event.keyCode:event.which;
if ((keycode == 32) || (keycode >= 47 && keycode <= 57) || (keycode >= 65 && keycode <= 90) || (keycode >= 97 && keycode <= 122)) {
return true;
}
else {
alert("Sorry You can not insert Special Character");
return false;
}
return true;
}

Categories

Resources