I'm trying to prevent user from entering anything except numbers and letters, but my code doesn't even allow them itself. What could be the reason? Here's my code snippet:
$(document).ready(function(){
$("#txtuname").keypress(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
JSFiddle
$(document).ready(function () {
$("#txtuname").keypress(function (e) {
var validExp = /^[0-9a-z]+$/gi;
if (validExp.test(e.key)) {
$("#errmsg").html("");
return true;
}
else {
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
You can use keyup not keypress
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You can substitute input event for keypress event; adjust RegExp to /[0-9a-z]/i, use .split() with parameter "", Array.prototype.every(), RegExp.prototype.test() to check each character of input value at if condition; if each character is a digit or a letter condition is true, else false replace invalid characters of value using .replace() with RegExp /[^0-9a-z]/ig
$(document).ready(function() {
var validExp = /[0-9a-z]/i;
$("#txtuname").on("input", function(e) {
var val = this.value;
var check = val.split("").every(function(value) {
return validExp.test(value)
});
if (check) {
$("#errmsg").html("");
return check;
} else {
this.value = val.replace(/[^0-9a-z]/ig, "");
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You issue is you are not getting the value of the key that is being pressed. If you set the val variable like so, it will work as expected.
var val = String.fromCharCode(e.keyCode)
This gets the ASCII code of the key pressed, and then converting to the letter or number it represents. Then you can check against your regex.
This is because keypress events are fired before the new character is added to the value of the element (so the first keypress event is fired before the first character is added, while the value is still empty). You should use keyup instead, which is fired after the character has been added reference.
Here is the code
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
js
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(val.match(validExp))
{
$("#errmsg").html("");
return true;
}
else
{
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
$(document).ready(function(){
$("#txtuname").keyup(function(e){
var validExp = /^[0-9a-z]+$/gi;
var val = $(this).val();
if(validExp.test(val))
{
$("#errmsg").html("");
return true;
}
else
{
// fix the value of input field here
$(this).val("");
$("#errmsg").html("Number and letters Only");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="txtuname" id="txtuname" />
<span id="errmsg"></span>
You need to use keyup so that the character is "added" already to the value if you're going to use this given technique.
Since String.prototype.match actually returns an array of the match, it won't work in the way you want it to. Not to mention that it is much more expensive than RegEx.prototype.test.
Bonus
You can use the technique of finding carret position in an input field shown in Get cursor position (in characters) within a text Input field
To actually fix the input field on keyup.
Related
I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">
I have a simple first/last name form. When submitted I want to check that only letters have been used and if not, display an error div.
For example:
if ('#input-32' ) {
/* contains anything other than letters */
$("#error").show();
}
You can use Regex - Read More
const input = document.querySelector('#firstname');
input.addEventListener('input', function(e) {
const val = e.target.value;
const isLetter = /^[a-zA-Z]+$/.test(val);
console.log(isLetter);
// if( isLetter ){ ... }
})
<input type="text" id="firstname">
The following should show the error element if input contains anything other than letters:
if ($('#input-32').val().match(/[^a-zA-Z]/g)) {
/* contains anything other than letters */
$("#error").show();
}
$(document).ready(function(){
$("#error").hide();
$("#nameField").on("change", function(){
var nameSub = $('#nameField').val();
if(/^[a-zA-Z]+$/.test(nameSub)){
$("#error").hide();
}
else{
$("#error").show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="nameField"/>
<div id="error">error</div>
I have a JavaScript function to Validate only decimal value.I use the JavaScript onkeyup event.
function onlyNumeric(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var exclusions = [8, 46];
if (exclusions.indexOf(key) > -1) {
return;
}
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) {
theEvent.preventDefault();
}
return false;
}
return true;
}
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
It's working fine when I put value not from the number pad. But when I put value by number pad it's not working. So how can i fixed it?
Also I need fix it at two decimal point. But how can I do it?
Is onkeyup event Ok for this purpose?
Below is the code to help you out:
function onlyNumeric(evt) {
var pattern = /^\d{0,4}(\.\d{0,2})?$/i;
var element = document.getElementById("ColumnName");
if(pattern.test(element.value)) {
console.log("Vadid number:" + element.value);
} else {
console.log("Invadid number:" + element.value);
}
}
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
You can use this Regex pattern :
/^\d+(?:\.\d{1,2})?$/
Explanation :
\d match a digit...
+ one or more times
( begin group...
?: but do not capture anything
\. match literal dot
\d match a digit...
{1,2} one or two times
) end group
? make the entire group optional
<input type="text" onkeyup="onlyNumeric(event)" class="form-control" id="ColumnName" name="ColumnName">
<script>
function onlyNumeric(evt) {
var rx = /^\d+(?:\.\d{1,2})?$/;
var ele = document.getElementById("ColumnName");
if(rx.test(ele.value)) {
console.log("true");
}else{
console.log("false");
}
}
</script>
Another solution using addEventListener() instead of onkeyup:
<input type="text" class="form-control" id="ColumnName" name="ColumnName">
<script>
function onlyNumeric(evt) {
var rx = /^\d+(?:\.\d{1,2})?$/;
var ele = document.getElementById("ColumnName");
if(rx.test(ele.value)) {
console.log("true");
}else{
console.log("false");
}
}
var el = document.getElementById("ColumnName");
el.addEventListener("input", onlyNumeric, false);
</script>
Use this jquery plugin it validate decimal behaviour while typing and mouse click
https://github.com/sarkfoundation/Decimal-Behavior
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type='text/javascript' src="https://rawgit.com/sarkfoundation/Decimal-Behavior/master/sark-decimal/sark-decimal.js"></script>
<input type="text" data-behaviour="decimal">
MY CODE
function validate(e, id) {
var reg = new RegExp('^\\d+$');
if (reg.test($("#" + id).val())) {
var value = $("#" + id).val();
alert(value);
} else {
alert("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="number" id="number-input" oninput="validate(event,'number-input');">
This accept 1.(dot after any digits) value rest all is good.
You can try using <input type="tel" ...>. This way when user types 1. you will receive 1. only and not 1 and it will also open number keypad on mobile.
function validate(e, id) {
var reg = /^[0-9]*(\.(?=[0-9]+))*[0-9]+$/;
var value = $("#" + id).val();
if (reg.test(value)) {
console.log(value);
} else {
console.log("fail");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="tel" id="number-input" oninput="validate(event,'number-input');">
You can also refer to How to get the raw value an <input type="number"> field? for more information in why 1. returns 1 and not 1.
It work as fallow:
1 pass
1. fail
1.1 pass
function validate(e, id) {
var value = $("#" + id).val() + "";
if (new RegExp('^[0-9]+\.[0-9]+$').test(value)
|| ((new RegExp('^[0-9]+').test(value) && !value.includes(".")))
) {
var value = $("#" + id).val();
alert($("#" + id).val() + "->" + value);
} else {
alert("fail " + $("#" + id).val());
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input name="input-type" type="text" id="text-input" oninput="validate(event,'text-input');">
Here is a code that might help you.In the below code when the user types . it is replaced by null.It only accepts digits.This is for input type="text".The variable currValue has the value of the input.
The search() method searches a string for a specified value, and returns the position of the match.The search value can be string or a regular expression.This method returns -1 if no match is found.
Then I am using .replace()
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
Here I am replacing it with null if the regex doesn't match.The regex [^0-9] checks if not digit.
JSFIDDLE
Here is the code:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label>Digits Only:
<input type="text" />
</label>
<br>
<br>
EDIT :
In input type="number" we have to force it to always accept the updated val since many events does not work in it.So for that reason I have to update the existing value with the updated value after each event.
So I added
var v = $(this).val();
$(this).focus().val("").val(v);
So that each time the input is focused the value get updated with the existing value.
UPDATED FIDDLE FOR INPUT TYPE NUMBER
Updated snippet:
$(function() {
$('input').bind('keyup input', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
if (currValue.search(/[^0-9]/) != -1) {
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" />
</label>
<br>
<br>
EDIT 2 : For special case + and -.I think its a bug I am not sure but check the below snippet.It works for all the cases.Hope it helps.
FINAL FIDDLE
$(function() {
$('input').bind('keyup', function(event) {
var v = $(this).val();
$(this).focus().val("").val(v);
var currValue = $(this).val();
$(this).val(currValue.replace(/[^0-9]/, ''));
alert(v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Digits Only:
<input type="number" name="test" min=0 save="" oninput="validity.valid ? this.save = value : value = this.save;">
</label>
<br>
<br>
Hope it helps.For any other doubt feel free to ask.
http://jsbin.com/cunejafehe/edit?html,js,console,output
var reg = /^[a-zA-Z\d\s\-'#(),"]*$/;
function myFunction(e){
console.log(e.value);
if(reg.test(e.value))
{
return false;
}
}
<input onkeyup="myFunction(this)" type="text">
I wonder why above code doesn't work, what I want to do is allow only these character to be in the input : a-z and 1-9 including 0, and these character -'#(),"
Please have a look at this approach. Here i am passing an event object instead of DOM element reference and then we are checking it against Regx expression.
var reg = /^[a-zA-Z\d\s\-'#(),"0-9]*$/
function myFunction(e){
var c = String.fromCharCode(e.which)
console.log(c);
if(reg.test(c))
{
return true;
}
else
return false;
}
$(document).ready(function(){
$( "#mytextbox" ).keypress(function( e) {
return myFunction(e);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Inline function : <input onkeypress="return myFunction(event)" type="text">
<br/>
Binding a function : <input id="mytextbox" type="text">
The test method belongs to a RegExp object, since you're not using that you should change reg.test(c) to c.match(reg) inside myFunction.
Moreover you are working on the full value of the field by passing this. I guess you can do something like this, even if not very elegant:
var reg = /^[a-zA-Z\d\s\-'#(),"]*$/;
function myFunction(e){
if (!e.value.match(reg)) {
e.value = e.value.slice(0, -1);
}
}
<input onkeyup="myFunction(this)" type="text">