For my html, I'm trying to validate a form with a postcode input.
But this input is not working (or not being recognized). For my postcode input, I want to text box to only accept numbers.
Postcode input:
var Postcode = document.forms["Rego"]["postcode"].value;
var e = Postcode;
var code = e.keyCode;
if (code > 47 && code < 58) || code == 40 || code == 41 || code == 43) {
return true;
}
alert("Invalid Postcode. Please enter numbers only.");
return false;
What am I doing wrong?
In your condition if in line 4 after 58 why you close the ) ???
You are doing quite a few things wrong. You are not setting an event handler, you are actually binding to the value in the input box. You have to first get the DOM element representing the text box, then bind an event handler to the DOM element. Try this:
var Postcode = document.getElementById('post');
Postcode.onclick = function(e) {
console.log(e);
var code = e.keyCode;
if (code > 47 && code < 58 || code == 40 || code == 41 || code == 43) {
return true;
}
alert("Invalid Postcode. Please enter numbers only.");
e.preventDefault()
return false;
}
Fiddle: http://jsfiddle.net/S47gV/
To only accept numbers, you can use (for HTML5):
<input type="number" name="whatever">
Plus, if you want to validate it with js (doing so in browser is not recommended as anyone can modify your js file and push the contents to the server) or server code, here's some insight:
Try to convert the string passed to the server into a number. For example, in python you can do: int(whatever). If the conversion fails, that means the string isn't a number.
Hope that helps :)
If you use HTML5 you can set this automatically.
<input type="number" name="quantity" min="47" max="58">
By using below code textbox/inputbox allow only numeric value
$j('#inputbox_id').keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
e.preventDefault();
}
}
});
and if you want to set length of textbox/input box then set "maxlength=5"
I think i have found what you are doing wrong:
You are reading postcode value from input type and then comparing its keycode.
However‚ it may work only when your input has single number and when you type more characters in it your postcode variable becomes something for example 5436 and then when you use keycode function on this in wont work as expected.
Related
I have written following function to restrict only numbers with the limit of 2 numbers (below 100).
The first part checks special charters and letters. I got stuck in else part.
And Now I am trying to restrict with only 2 digits numeric number (without decimal). But it doesn't work the logic in below code. I am not allowed to use input type =number in HTML. The html input type is text
$(".allownumericTwo").on("input", function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
$(this).val($(this).val().match(\d{0,2});
}
return true;
});
The input event is not cancelable. It also doesn't have a value for key code. What you could do instead is to check if the value is valid and if not reset it to its previous value. You also need to enclose your regex pattern between slashes, i.e. /^\d{0,2}$/.
e.g.
var oldValue = $(".allownumericTwo").val();
$(".allownumericTwo").on("input", function(evt) {
if (this.value.length > 0 && this.value.match(/^\d{0,2}$/) == null) {
this.value = oldValue;
} else {
oldValue = this.value;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='allownumericTwo'>
you can use isNumeric()
if($(this).val().length < 3)
{
if($.isNumeric($(this).val())){
//do something
}
}
This May help.
Do remember the match returns an array.
function printFirstTwoNumbers(val) {
var regex = /^\d{0,2}/g;;
console.log(val.match(regex));
return true;
}
printFirstTwoNumbers('288.80');
printFirstTwoNumbers('2.80');
printFirstTwoNumbers('29898.80');
printFirstTwoNumbers('300');
I've an input box that I only want to allow letters, hyphen, space and backspace. All is good on chrome but on Firefox backspace (or charcode 8) does not work. - https://jsfiddle.net/npo7y7fr/
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45)) return false;
});
});
I've tried adding && (key.charCode != 8) also changes keypress to others like 'keydown, keyup' etc...
Can anybody get this working in Firefox (40.0.3) or something that I can use instead?
Since Space will send keycode 32 and backspace will send 0 in Mozilla so that's why it is not working in mozilla.
change your script as below
$(document).ready(function () {
$('.textInput').keypress(function (key) {
if ((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && (key.charCode != 45) && (key.charCode != 32) && (key.charCode != 0) ) return false;
});
});
hope this helps..!!
Instead of hardcoding some special keys, just skip the filtering for all of them. With the accepted solution, you still cancel arrow keys, Home, End, etc., which is a bad thing for the user.
As all special keys have a key field longer than 1 character, you can safely do this:
$(document).ready(function () {
$('.textInput').keypress(function (event) {
return event.key.length > 1 || event.ctrlKey || !!event.key.match(/[a-zA-Z \-]/);
});
});
The pressed key is accepted if it's a special key, it's been pressed simultaneously with the Ctrl key (to allow copying and pasting) or if it matches the regular expression (letters, space and hyphen).
As the user can paste invalid content, you should still remove illegal characters with the oninput event (probably something like ctrl.value.replace(/[^a-zA-Z \-]+/g, '')).
Rather than trying to control what the browser can enter into the input, it might be easier to just filter the contents of the textbox on keyup.
Consider the following:
$('.textInput').keyup(function() {
$(this).val( $(this).val().replace(/[^a-zA-Z]/,''));
});
Hope this helps.
I am developing a website and I want to read the input from the bar code.
While I am getting the input from bar code keyboard input should not be considered as a input since when I am trying to get the integer inputs key board is giving inputs.
below is the code which I tried with:
$(document).keydown(function(e) {
if (e.altKey & (e.which > 47 && e.which < 58)) {
var value = "";
value += String.fromCharCode(e.which);
window.location = "../../patient_overview_c/view/" + value;
}
});
I want to get the input while I am pressing the alt key. I have done this for only one digit vale. I want to go for two or more digits.
You are having one ampersand instead of two, on your second line. The e.altKey returns a bool.
Change
if (e.altKey & (e.which > 47 && e.which < 58)) {
^
into
if (e.altKey && (e.which > 47 && e.which < 58)) {
^
I am facing problem in validation. It is working in google chrome, but not in Mozilla.
Like: I have a form where Name: ____ .
I want to put a validation so that the user can't write a numeric value.
Inside the javascript:
function checkerFunction1(e)
{
var charCode1=e.which || e.keyCode;
if((charCode1 >= 65 && charCode1 <= 90) ||(charCode1 >= 97 && charCode1 <= 122) ||(charCode1==32 || charCode1==8 || charCode1==46))
return true;
return false;
}
Inside the jsp page:
<input type="text" value="Name" onkeypress="return checkerFunction1(window.event)"/>
Why it is not working in Mozilla?
This should fix it:
function checkerFunction1(e)
{
e = e || window.event;
var charCode1=e.which || e.keyCode;
return ((charCode1 >= 65 && charCode1 <= 90) ||(charCode1 >= 97 && charCode1 <= 122) ||(charCode1==32 || charCode1==8 || charCode1==46))
}
The condition in the if's brackets is a boolean already. The if is not needed when you want to return a true or false, you were basically saying:
if(true)
return true;
else
return false;
Firefox was telling me "e is undefined"
You'll need to use the event object for that browser (as seen above)
preventDefault() is not needed. Returning false will prevent Firefox from entering a false key into the field.
You have forgotten to call e.preventDefault().
function checkerFunction1(e) {
e = e || window.event;
var charCode1=e.which || e.keyCode;
if(
(charCode1 >= 65 && charCode1 <= 90)
|| (charCode1 >= 97 && charCode1 <= 122)
|| (charCode1==32 || charCode1==8 || charCode1==46)
) return true;
return e.preventDefault(), false;
}
see this fiddle.
It is better practice to attach event listeners to DOM elements on window load rather than via html attributes as it separates your HTML from your JavaScript. It also has the added benefit of choosing when you want to capture the event itself.
You can still grab window.event inside the function if absolutely required for compatibility.
The "undefined problem" in Firefox comes from event being treated more like a keyword than a variable, so window.event === undefined but event !== undefined, therefore if you want to keep the thing as an attribute, you could do it like this
onkeypress="return checkerFunction1(window.event||event)"
I have written some JavaScript and jQuery code that accepts only numeric input in a textbox.
But this is not enough; I need to limit the input to certain numbers.
This textbox needs to deal with SSN numbers (Swedish SSN), and it has to start with 19 or 20. I want to force it to start with these numbers, but I can't manage to limit it to these.
$('input.SSNTB').keydown(function (event) {
var maxNrOfChars = 12;
var ssnNr = $('input.SSNTB').val();
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))) {
console.log("if-1");
event.preventDefault();
}
if (event.shiftKey == true) {
console.log("if-3");
event.preventDefault();
}
//rules to make sure the textbox starts with correct number
if (event.keyCode != 49 || event.keyCode != 50 || event.keyCode != 97 || event.keyCode != 98) {
console.log("if-4, Keycode:" + event.keyCode);
event.preventDefault();
}
}
});
The last if-case is executed to for testing this it is. It is executed as planed but it wont limit the input chars as its built for.
any tips or ideas?
You can use regex to limit the user to only inputting numbers and dashes. Using regex has the advantage that users can more naturally interact with the input, for instance they can paste into the text input and it will be validated successfully:
//bind event handler to the `keyup` event so the value will have been changed
$('.SSNTB').on('keyup', function (event) {
//get the newly changed value and limit it to numbers and hyphens
var newValue = this.value.replace(/[^0-9\-]/gi, '');
//if the new value has changed, meaning invalid characters have been removed, then update the value
if (this.value != newValue) {
this.value = newValue;
}
}).on('blur', function () {
//run some regex when the user un-focuses the input, this checks for the number ninteen or twenty, then a dash, three numbers, a dash, then four numbers
if (this.value.search(/[(20)(19)](-)([0-9]{3})(-)([0-9]{4})/gi) == -1) {
alert('ERROR!');
} else {
alert('GOOD GOING!');
}
});
Here is a demo: http://jsfiddle.net/BRewB/2/
Note that .on() is new in jQuery 1.7 and in this case is the same as using .bind().
Thought I would post the solution that came to the end. I actually kept the similar code that I posted above and did not covert this it RegExp. What was done was to verify the number after focus on this textbox is lost. It it is incorret the user will be informed and forced to fill in a valid number.
$('input.SSNTB').focusout(function () {
var ssnNr = $('input.SSNTB').val();
var ssnNrSub = ssnNr.substring(0, 2);
//console.log(ssnNrSub);
//checks for correct lenggth
if (ssnNr.length < 12) {
$('div.SSNHelp label.Help').html('SSN to short. Please fill in a complete one with 12 numbers');
setTimeout(function () {
$('input.SSNTB').focus();
}, 0);
validToSave = false;
return;
}
//checks so it starts correct
if (ssnNrSub != "19" && ssnNrSub != "20") {
$('div.SSNHelp label.Help').html('The SSN must start with 19 or 20. Please complete SSN.');
setTimeout(function () {
$('input.SSNTB').focus();
}, 0);
validToSave = false;
return;
}
$('div.SSNHelp label.Help').html('');
validToSave = true;
});
Works for me. : ]
You have to use regex. Regex is of help in these kind of situations.
Learn more about it from https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp