Credit card expiration date: mm/yy
Whenever I enter two numbers, I need add /, but currently when I delete the third number, he will only delete one number. How can I delete the third number along with the slash?
Please help thank you.
var characterCount
$('#expiry').on('input', function(e) {
if ($(this).val().length == 2 && characterCount < $(this).val().length) {
$(this).val($(this).val() + '/');
}
characterCount = $(this).val().length
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="expiry" type="text" />
with plain js
const inp = document.querySelector('#expiry')
inp.onkeydown = function() {
const key = event.keyCode || event.charCode;
if (key !== 8 && key !== 46 ) {
if (inp.value.length == 2) {
inp.value= (inp.value+'/');
}
}
if (( key == 8 || key == 46 ) && inp.value.length === 4) {
inp.value = inp.value.slice(0,3)
}
};
<input id="expiry" type="text" />
You can add an additional keyup event and when the backspace key is hit, remove any trailing slash from the end of the value.
I'd also recommend to set the maxlength, pattern and inputmode attributes on the input.
var characterCount;
$('#expiry').on('input', function(e) {
if ($(this).val().length == 2 && characterCount < $(this).val().length) {
$(this).val($(this).val() + '/');
}
characterCount = $(this).val().length
}).on('keyup', function(e) {
if (e.which === 8) {
$(this).val($(this).val().replace(/\/$/, ''))
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="expiry" type="text" maxlength="5" pattern="^\d{2}/\d{2}$" inputmode="numeric" />
Related
I am using a input of type number in which it allows multiple decimal points so i have tried using the regex not to allow more than one decimal point but even after using the regex i am facing the same issue can anyone tell me how to allow only one decimal point in input of type number in ionic1
Html:
<input stopccp focus-me class="inputContainer trade_input" type="number" name="" ng-model="vm.total_amount[$index]" ng-change="vm.onTotalCost()" limit-char limit="5" ng-keyup="vm.decimalcheck(vm.total_amount[$index])" >
Regex in function:
function decimalcheck (element) {
$log.log('decimalcheck got called', element);
var regex = /\d*\.?\d?/g;
return regex.exec(element);
}
Try this Regex:
^\d*\.?\d+$
Click for Demo
Explanation:
^ - Start of String
\d*- 0+ digits
\.?- 0 or 1 decimal point
\d+- 1+ digits(thus making it mandatory to have atleast one digit after the decimal point, if it is present)
$- End of String
OUTPUT:
<input type="text" pattern="\d+\.?\d?(?!\d)" />
Script
$('.number').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 1) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 1)) {
event.preventDefault();
}
});
$('.number').bind("paste", function(e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
e.preventDefault();
$(this).val(text.substring(0, text.indexOf('.') + 3));
}
}
else {
e.preventDefault();
}
});
HTML
<input type="text" class="number" />
Here is your answer
I think you just miss start(^) and end($) operator
function decimalcheck (element) {
$log.log('decimalcheck got called', element);
var regex = /^\d*\.?\d?$/g;
return regex.exec(element);
}
Try this in your html, It worked for me
pattern = "^\d*\.?\d+$"
like this:
<input stopccp focus-me class="inputContainer trade_input" type="number" name="" ng-model="vm.total_amount[$index]" ng-change="vm.onTotalCost()" limit-char limit="5" ng-keyup="vm.decimalcheck(vm.total_amount[$index])" pattern="^\d*\.?\d+$">
this work with input field use pattern and event onInput
<input
maxLength={4}
type="text"
pattern="\d+\.?\d?(?!\d)" // [0-9]*\.?[0-9]*
value={unitProgress}
onInput={(e: any) => {
const valueChange = e.target.validity.valid
? e.target.value
: unitProgress;
setUnitProgress(valueChange);
}}
/>
I want to check if a user inputs an invalid character when chosing his name. My code almost works. The only problem is when I type in a valid user name f.e. "John" and add an invalid character to it "John!!" it doesn't detect it. When I type in an invalid character only "!!!!" it gets detected.
HTML:
<input class="user-input" pattern="[a-zA-Z0-9._-ßÄÖÜäöü]{1,30}" type="text" id="idUsername" oninput='checkValidUsername();'" required disabled>
JavaScript:
function checkValidUsername()
{
var input = document.getElementById("idUsername").value;
if(input.search(/^[a-zA-Z0-9ßÄÖÜäöü_.-]/) == -1)
{
document.getElementById("idValidChars").style.visibility = "visible";
}
else
{
document.getElementById("idValidChars").style.visibility = "hidden";
}
}
You will have to change your regular expression to
/^[a-zA-Z0-9ßÄÖÜäöü_.-]+$/
This is because you need to check the whole string for a validity, instead of the first character as you did.
The + allows the previous sequence to appear more than one occurrence, and the $ restricts it to be the end of the string. Which means, that the string must start and end with only the characters you have indicated.
Try this:
$('#ID').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="ID" type="text" />
(XXX) XXX-XXXX xXXXX
I want insert a X symbol after every 15th character in input. I have a Business Phone input box. When a user is typing and reaches each 15th character, then jQuery will insert a hyphen (X).
For example: (999) 999-9999 x9999
I'm trying some codes and i think i'm so close to correct code but i have some problems. Here is my code sample;
$(document).delegate('#businessPhone', 'keyup', function(e) {
var Textlength = $(this).val();
console.log(Textlength.length);
if (Textlength.length >= 14) {
//alert("if"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999 x9999");
return false;
} else {
//alert("else"+Textlength.length);
$("#businessPhone").mask("(999) 999-9999");
}
});
Code is working fine as aspected if user complete enter all characters.
But problem is user wants to remove characters the characters did not delete if character length reach 14 .
try this
$('#phone-number', '#example-form')
.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
if ($phone.val().length === 15) {
$phone.val($phone.val() + ' x');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
<form id="example-form" name="my-form">
<label>Phone number:</label><br />
<!-- I used an input type of text here so browsers like Chrome do not display the spin box -->
<input id="phone-number" name="phone-number" type="text" placeholder="(XXX) XXX-XXXX" /><br /><br />
<input type="button" value="Submit" />
</form>
I have a textbox and it contain a value "Given Name". I want to disable first character of a textbox so that user cannot change the First Charcter in textbox by using backspace or any other means.
For Example: suppose textbox contains the value "Given Name". I want that user cannot change the First character "G" by using backspace or any other means.
<input type="text" id="nameId" onkeydown="validate(this.val)"/>
Below is javascript function:
function validate2(val) {
// have no idea how to do.
}
I have no idea how to do it in Javscript or Jquery.
You could do like follow :
$("#nameId").on("keydown", function(e) {
// if user writes a char at index === 0 that is not an arrow or HOME or END
if (($(this).get(0).selectionStart === 0 && (e.keyCode < 35 || e.keyCode > 40))
// or if user tries to erase first char
|| ($(this).get(0).selectionStart === 1 && $(this).get(0).selectionEnd === 1 && e.keyCode === 8)) {
// don't write the character
return false;
}
});
// prevent right click
$("#nameId").bind("contextmenu", function(e) {
e.preventDefault();
});
JSFIDDLE
Wasn't planning on answering, leaving it with the comment, but after seeing the other answers thought I might have a quick go at it after all:
The html:
<input type="text" id="nameId" value="Given Name" onkeydown="save(this,event)" onkeyup="restore(this,event)" onchange="restore(this,event)"/>
The javascript:
function restore(el,event) {
if(el.value.length == 0){
el.value = el.dataset.value.substr(0,1);
}else{
el.dataset.value = el.value;
}
}
function save(el,event) {
var key = event.which || event.charCode || event.keyCode;
if((key === 8 && el.value.length === 1)
|| (key === 46 && el.selectionStart == 0 && el.value.length === 1)){
event.preventDefault();
}
if(el.value.length > 0){
el.dataset.value = el.value;
}
}
The approach was to not mess around too much with preventing the deletion of the actual character (just the very bare basics) and instead ensure that if somebody deletes the first character to always restore it somehow. It creates code that's easy to comprehend and maintain, yet works quite neatly. A fiddle can be found here as well. Do note though that event.which is not the most cross browser consistent interface, so either use jQuery for that or check in other browsers before using it in production. Edited it in a way that should work cross browser including older browsers.
Here's mine version.
Html
<input type="text" id="nameId" value="Given Name" />
JS
var lastentry = '';
$("#nameId").on("keyup", function(e) {
var targetValue = $(e.currentTarget).attr('value');
var targetValueLength = targetValue.length;
var inputValue = this.value;
if(checkChanges(targetValueLength, targetValue, inputValue))
this.value = targetValue + lastentry;
else
lastentry = this.value.slice(targetValueLength)
});
function checkChanges(targetValueLength, targetValue, inputValue)
{
for(var i = 0; i < targetValueLength ; i++)
{
if(targetValue[i] != inputValue[i])
return true;
}
return false;
}
Demo
You can try this:-
<input type="text" id="nameId" value="Given Name" onkeydown="validate(this.value,event)"/>
<script>
function validate(val,event) {
// have no idea how to do.
if(event.target.selectionStart != undefined && (event.which === 46 ||event.which === 8)){
var startPos = event.target.selectionStart,
endPos = event.target.selectionEnd;
console.log(startPos,endPos);
if(startPos === 0 && startPos != endPos){
var restPart = val.slice(endPos,val.length);
if(restPart){
val = val[0].concat(restPart);
} else{
val = val[0]
}
event.target.value = val;
event.preventDefault();
} else if(startPos === 0 && startPos === endPos && event.which === 46){
event.preventDefault();
} else if(startPos === 1 && event.which === 8){
event.preventDefault();
}
}
}
</script>
Hi use this it do not allow to delete first character ,
$(document).keydown(function(e)
{
var value = $('#nameId').val().length;
if ( e.keyCode == 8 && value < 2)
e.preventDefault();
});
I wanted a text field to take only numbers ans some control keys and number should be exactly four digit long, not less not more. My validation code is
function checkValidInput()
{
$(".validateYearTextBox").keydown(function(event)
{
// Allow only delete, backspace,left arrow,right arraow and Tab
if (
event.keyCode == 46 //delete
|| event.keyCode == 8 //backspace
|| event.keyCode == 37 //leftarow
|| event.keyCode == 39 //rightarrow
|| event.keyCode == 9 //tab
)
{
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode <96 ||event.keyCode > 105) ) {
event.preventDefault();
}
}
});
$(".validateYearTextBox").keyup(function(event)
{
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, valore.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
}
Here, my first validation is working, but my send one is not working.
I am calling this validation function in my aspx page like this
<script type="text/javascript">
$(document).ready(function(){
checkValidInput();
}
</script>
What is going wrong?
Simplify it:
function checkValidInput() {
// Allow only delete, backspace, left arrow, right arrow,
// Tab, ctrl+v and numbers
$(".validateYearTextBox").keydown(function(event) {
if (!((event.keyCode == 46 ||
event.keyCode == 8 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 9) ||
(event.ctrlKey && event.keyCode == 86) || // Edit: Added to allow ctrl+v
$(this).val().length < 4 &&
((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105)))) {
// Stop the event
event.preventDefault();
return false;
}
});
// Edit: Added validate after copy+paste.
// This removes non-numeric characters and truncates the length
// to 4 if the user copy + pasted.
$(".validateYearTextBox").change(function(event) {
var value = $(this).val();
value = value.replace(/[^0-9]/g,'');
value = value.substr(0,4);
$(this).val(value);
});
}
$(document).ready(function() {
checkValidInput();
});
http://jsfiddle.net/nwellcome/687kD/
Edit: Personally I like the Masked Input jQuery plugin but that might be a heavy-handed solution if this is all you need to do.
There are many, many jQuery plugins that already do this in one form or another.
One that does mostly1 what you want is Masked Input Plugin. If you can, I recommend using something existing, working and proven, rather than reinventing.
1 The only part that it doesn't seem to do is display an error if a user tries to enter more than n characters but I'm sure you could modify the plugin or add a length check to the <input>
Use regular expression :
enter code here
function validator(elem,msg)
{
var exp=/^([0-9]+)$/; //it only allows for numbers
if(elem.value.match(exp))
{return true;}
else
{
alert(msg);
elem.focus();
return false;
}
}
the html code :
enter code here
<html><head>
<script src="javasript.js" type="text/javascript">
</head>
<body>
<form method=POST>
<input type='text' maxlength=4 name='num' id='num'>
<input type='submit' value=OK onClick="validator(document.getElementById('num'),'Only four numbers and numbers only!');">
</form> //the maxlength in input text tag restrict the maximum length of the input
</body></html>
Here's a simple way of doing it. Stores the old text before an event changes the text. Then check to see if the new text is valid or not. If it isn't, then revert back to the old text. To further ensure the maximum of 4 characters, add a maxlength attribute to all <input type="text"> elements.
jQuery.fn.forceNumericOnly = function() {
return this.each(function() {
var oldText;
$(this).keyup(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(oldText);
else
oldText = $(this).val();
})
$(this).blur(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(newText = oldText);
else
oldText = $(this).val();
});
})
};
$(".validateYearTextBox").forceNumericOnly();
if (document.ExamEntry.examnum.value=="") {
msg+="You must enter your examination number \n";
document.ExamEntry.examnum.focus();
document.getElementById('examnum').style.color="red";
result = false;
}
$('.numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
}).on('paste',function(e){ e.preventDefault();});
Here add class=numeric to input text box'. it will allow only 4 digits if you want to limit size to 2 digits change to e.delegateTarget.value.length>1 and so on as index starts from zero
Use HTML input maxlength attribute for this and also set the size value of fixing width 4 in same input size attribute.
<input type="text" maxlength="4" size="4">
Here is a simple answer that takes care of copy paste and all.
$(document).on("input", ".validateYearTextBox", function() {
var value = this.value
value = value.replace(/\D/g,'');
for (i = 0; i < value.length; i++) {
if (i > 3) {
value = value.replace(value[i], '')
}
}
});