Allow only numbers and multiple dots in jquery form input - javascript

I wanted to know a way to allow only numbers and multiple dots in using jquery in a form input.
The scenario is that the form input holds a version name and version name can have values like 6.0.2345 and as far as my research went, I could get only the numbers working by the following code:
$('.number').keydown(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/do
});
But this allows only numbers and does not allow me to use backspace or delete. Any workaround from this method that I can use so that I can allow only multiple dots and numbers in the input file.

Finally arrived at this answer which works.
$(".submit").on('click',function(e){
e.preventDefault();
var test_val = $(".test").val();
var test_regex = /^(\*|\d+(\.\d+){0,3}(\.\*)?)$/i;
if(!test_regex.test(test_val)){
alert("This is not a valid entry");
}
});

<input onKeyPress={(event) => { if (!/[0-9.]/.test(event.key)) { event.preventDefault(); } }}

Related

How to allow only numbers in a textarea using jQuery?

I've seen a similar question on SO but my approach is slightly different. I have a textarea that I want to accept only numbers as an input. Currently all inputs are allowed and the error alert isn't triggered.
I think the problem may be that the key being pressed isn't being passed into my validate function, but I'm not sure how to do that without using the html onkeypress which I'm trying to avoid using.
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
$(document).ready(function () {
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate() {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. '1', '2' etc.")
return false;
}
}
noteNumberInput.addEventListener("keypress", validate);
});
Your function needs the key parameter:
function validate(key) {
....

Regular Expression max-length is not working

function test() {
var regex = new RegExp("^[0-9]{1,11}$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
It is correct to take only integer but max-length is not working. It takes more than 11 digits.
This kind of manual input validation is not how applications are usually written these days in HTML5. It is a throwback to the bad old jQuery days. It is a bad user experience to simply throw away keystrokes--the user has no idea what he is doing wrong, and may think his keyboard is broken. If you trap on the keyup event, you will also miss some scenarios, such as when the user has dragged and dropped text into the input box. Or if the user types CTRL+V to paste text into the box, you will end up looking at that keystroke instead of the characters pasted in.
HTML5 adds the pattern attribute to the input element which allows you to do regexp-based validation. This has a number of advantages. For instance, invalid entries can be styled using CSS with the :invalid pseudo-class. Invalid form entries will automatically prevent submits, and put up user-friendly balloons describing the specific problem.
In your case:
<input pattern="\\d{1, 11}">
Note that no ^ or $ anchors are required--they are implicit in this case.
No JS is required.
as you said:
I want to give permission only to write digits and max length should be eleven(11) digits.
you can:
use an <input type="number" maxlength="11" />
use a regex /^\d{1,11}$/
document.addEventListener('DOMContentLoaded', function() {
function valueIsValid(v) {
return /^\d{1,11}$/.test(v);
}
var foo = document.querySelector('#foo');
foo
.addEventListener('change', function() {
console.log('valid', valueIsValid(foo.value), foo.value)
})
;
});
<input id="foo" />
This is what I understood from your question. Try something like this.
var count = 0;
function test() {
var regex = new RegExp("^[0-9]{1,11}$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if(count<11){
if (!regex.test(key)) {
count=0;
event.preventDefault();
return false;
}
count++;
}
return false;
}

Unable to enter only Mobile Number in inputText with Country Code Not Other Chars in primefaces : +NN-NNNNNNNNNN

I want to make input text box in primefaces which only can take mobile number with country code. The format is +NN-NNNNNNNNNN, e.g., +91-9876123456. User could not type any other characters except the mentioned. I've tried with some Javascript, but the result did not satisfy me.
By, How to disable special characters and alphabets in Primefaces input text?
In this question, they have mentioned all the thing is perfect, but delete and movement of cursor is not happened here.
Moreover I do not want to use inputMask, behavior of this component is not exact with the text, although you have any better suggestion with this component then kindly provide.
If you need to match that exact pattern, I would probably check on every keypress. Just make sure it's clear to the user that they need to match a pattern or they may get annoyed when their keys don't seem to work.
$("#test").on("keypress", function(e) {
var match = [48,49,50,51,52,53,54,55,56,57];
var insert = '';
if (this.value.length >= 14) {
return false;
}
if (this.value.length === 0) {
if (e.which === 43) {
return true;
}
insert = '+'
}
if (this.value.length === 3) {
if (e.which === 45) {
return true;
}
insert = "-";
}
if (match.indexOf(e.which) === -1) {
return false;
}
this.value += insert;
return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test"></input>
You should give a look at Forza, they did some really interesting implementation for phone input with forced synthax like +() ____ ____ :
http://forza.ndevrstudios.com/#/form-masks

Javascript validation C#.NET

I am having a problem validating a textbox to not allow spacing. When the user enters a space I would like it to display an alert message and then clear the textbox, but the textbox doesn't clear. This is what I have so far.
function ValidateSpace () {
var SerNum = document.getElementById("txtbox1")
if (event.keyCode == 32) {
alert("This field may contain no spaces.");
document.getElementById ("txtbox1").value=""
}
}
I have users trying to put multiple entries in this space but it should only accept one. The textbox is for inventory purposes so it would change the nature of the data if I were to remove spaces
I suppose that you have to bind keyDown event on textbox
try this jquery code to remove live the spaces
$("#IdOfTheTextBox").on("keydown", function (e) {
return e.which !== 32;
});​​​​​
If you can't use jquery try with this javascript function (onkeypress event of textbox)
function NoSpace() {
if (event.keyCode == 32) {
event.returnValue = false;
return false;
}
}
if you want to remove spaces after the input you can do this
var noSpaces = document.getElementById("txtbox1").value.replace(/\s/g, "");

How to use Javascript to filter and ignore keypresses on an input field?

I need to stop accepting input (keystrokes) on an HTML form input field when the length limit has been reached. In straight-up HTML I can do this with maxlength="3" or whatever the length is, but I would like to handle it through Javascript if possible so I can do it together with the next requirement.
I also need to filter the input so that if a field is numeric only numbers can be typed, and if there's a mask or regex any inputs conform to the mask/regex.
Is there a "standard" way to do this in, Javascript, particularly in Dojo 1.9? (I know everybody uses JQuery but we use Dojo because.)
For dojo, if you need any sort of validation, I would use the ValidationTextBox, which takes "maxLength" as a property AND allows for all sorts of nifty validation schemes. The reference for ValidationTextBox is here:
http://dojotoolkit.org/reference-guide/1.9/dijit/form/ValidationTextBox.html
I used pure Javascript because I am not familiar with Dojo, but these event listeners can probably be cleaned up with Dojo.
var input = document.getElementsByTagName('input')[0],
error = document.getElementById('error');
input.addEventListener('keypress', function(e) {
if(e.which < 48 || e.which > 57) {
e.preventDefault();
error.innerHTML = 'Must be a digit';
} else if(e.target.value.length >= 3) {
e.preventDefault();
error.innerHTML = 'Cannot be more than 3 digits';
} else {
error.innerHTML = '';
}
});
We listen to a keypress and then, to make sure it is a digit, we seek that the key pressed was between 48-57 (0-9). If not, then we prevent the key press and show an error. Then we check the input's current length. If it is too long, then prevent the key press and show an error. Otherwise, it worked and we allow the event and clear the error.
You maybe looking for this:
<input id="text" type="text"/>
$('#text').on('keypress',function(e){
var numero = this.value.length;
console.log(this.value.length);
if (e.which != 8 && e.which < 48 || e.which > 57)
{
return false
}
else if (numero === 3 && e.which != 8){
return false //alert user here
}else{
return true // allow backspace only (8)
}
}
);
DEMO

Categories