I have a JavaScript function that validates an input field and prevents the user from typing anything that doesn't match the condition. This function is based on event.keyCode.
I'm trying to modify the function to use a RegExp and validates not "per character" but "per whole input" so that it does the same, but with different conditions:
numeric only
allowed decimal "." or ","
Here is the function in its current form, using event.keyCode:
function isNumeric(evt, alertDIVid, alertMsg) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode >= 48 && charCode <= 57) {
document.getElementById(alertDIVid).innerHTML = '';
return true;
}
else {
document.getElementById(alertDIVid).innerHTML = alertMsg;
return false;
}
}
document.getElementById('AMNT').onkeypress = function(event) {
event = event || window.event;
return isNumeric(event, 'numericalert', 'Numeric values only!')
};
In order to do the kind of validation you want, you need to listen to the keyup event instead. This event fires after the field is changed, so that you know the new value of the field. You also need to know the previous value of the field so you can "reset" it if what the user typed turns out to be invalid.
For example:
(function() {
var previousValue = document.getElementById('myInput').value;
var pattern = /^\d*((\.|,)\d*)?$/;
function validateInput(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
// Valid input; update previousValue:
previousValue = newValue;
} else {
// Invalid input; reset field value:
event.target.value = previousValue;
}
}
document.getElementById('myInput').onkeyup = validateInput;
}());
Working demo: http://jsfiddle.net/8kUdG/
It's worth noting that this will also validate empty strings, as well as unfinished numbers, like 5, or 42. (otherwise the user would have to insert the decimal sign after typing the decimals, which would be... weird).
And finally, keep in mind that this might not be a cross-browser safe solution. If you need a pure-JavaScript solution, you will need to refine it (i.e., this might not work in IE).
Edit: of course, showing an error message instead of resetting the input field to the previous value is also perfectly possible (updated JSFiddle):
(function() {
var pattern = /^(?=.)\d*(?:[.,]\d+)?$/;
var error = document.getElementById('error');
document.getElementById('myInput').onkeyup = function(event) {
event = event || window.event;
var newValue = event.target.value || '';
if (newValue.match(pattern)) {
error.innerHTML = '';
} else {
error.innerHTML = 'Not a valid number!';
}
};
}());
I leave it up to you to replace the alert with something more user-friendly.
The easiest solution would be something like this
// Returns true on valid, false on invalid
function myInputFilter(input)
{
var value = input.value;
var regex = /^[\d\,\.]*$/;
if(!regex.test(value))
return false;
return true;
}
You could edit the function to just take a string argument, but I've chosen to have it accept the text input element instead. The RegEx can be replaced by anything, I've made a simple one for this example. I would refine it a bit if I were you (You can use the excellent online tool RegExr)
Here is an example of the filter implemented
http://jsfiddle.net/kVV77/
You can use following regular expression:
/^[+-]?(?=.)(?:\d+,)*\d*(?:\.\d+)?$/
to allow only any number of comma and only one dot . with the condition that number cannot start with a comma. Number can have optional + or - at the start.
Related
I am doing a decimal number input validation where I want to prevent typing 'point' for the second consecutive time
For example-
Above in the input box after keypress of the first period, I shouldn't be able to keypress it for the second consecutive time.
I have done this so far-
if (e.which === 190) {
if(value === '') {
e.preventDefault()
this.setState({[error]: "Only one period allowed in decimal numbers!"});
return false;
}
}
But this only prevents the 3rd keypress and allows the second period.
How do I prevent the keypress using JavaScript?
PS- I am using input field if type- 'number'. So the after I press the second dot the e.target.value becomes null.
You can use regular expression alongwith onChange event.
testHanlder = (event) => {
let value = event.target.value;
if (value) {
value = value.replace(/\.+/g, ".")
this.setState({value})
}
}
Even if it passes the second decimal number issue, it will still allow alphabets inside the input field.
Instead you could use:-
var textBox = document.getElementById("txt")
textBox.addEventListener("keyup",function(e) {
var floatValue = parseFloat(textBox.value) || ""
if(floatValue !== textBox.value) textBox.value = floatValue
})
i want to get the character typed into an html text input field on keypress
then validate the character entered against a list of characters
and return false if it isn't found in that list
(i don't want to use regular expressions)
by 'list' i mean this:
var acceptable = 'abcd12';
this would prevent, for example, the character 'e' being entered, and so on
the html would look like this:
<input id='someId' type='text' onkeypress='return check(this,event);'>
and the javascript:
function check(element,e) {
var acceptable = 'abcd12';
// now get what character was entered
// if it's in the list, return true
// if it's not in the list, return false
}
Generally, you would want to bind an onChange event handler to the input field like this:
jQuery('#someId').change(function() {
var acceptable = ['1', '2', 'a', 'b', 'y'];
var text = jQuery(this).val();
var allowed = true;
// Loop through each character in the string
var length = text.length;
for (var i = 0; i < length; i++) {
// This if condition is fulfilled if the character
// is not in the array of acceptable characters
if (jQuery.inArray(text[i], acceptable) != -1)
allowed = false;
}
if (allowed)
// The input is valid
else
// The input contains an unallowed character
});
IMPORTANT:
You always have to do server side verification of the data submitted via a form. Anyone can mess with the code in your script and the HTML code. There are many ways to send false data to your server, no matter what you do to prevent it. Therefore it is extremely important to always do server side verification, since the server environment is entirely in your control.
Side note
The onChange event handler only fires when the field loses focus. If this behaviour is undesirable for you, use this:
jQuery('#someId').on('change keypress paste focus textInput input',function(){
// The same code as above can be used here
}
See this link for more information on this.
If you create a variable chr with the character that was entered, then
acceptable.indexOf(chr) !== -1
will be true if the character is acceptable (in the string).
I'll propose a solution without regexes, although I don't understand that constraint.
Here is a logical proposal to validate your strings.
Take your input string, replace occurrences of each of the valid characters in it with '' (empty string), then just verify that the length is 0. If there are characters left (length > 0), validation doesn't pass.
Also note there are other ways of doing this. Modern browsers support the pattern attribute on text inputs, which will validate against a regex (which is trivial to write for this case).
Here is a demo of this in action.
HTML
<input type="text">
JavaScript
input = document.querySelector("input");
restrictChars(input, "abc");
function restrictChars(input, chars) {
input.addEventListener("keypress", function (e) {
e.preventDefault();
var character = String.fromCharCode(e.keyCode);
var isValid = chars.indexOf(character) != -1;
if (isValid) {
input.value += character;
}
});
}
Basically we prevent the default behaviour of the keypress event (to prevent typing) and use it to obtain the pressed key from the event.keyCode. Then, we test to see if that character is present in the chars parameter (without the use of unnecessary regex in my opinion), if it is, we simulate the normal behaviour by adding the character to the <input>'s value, if it's not, we do absolutely nothing, resulting in nothing getting typed.
Hope this helps!
I've made a small jQuery-based solution:
$(document).ready(function() {
$('#input').keypress(function(e) {
var allowed = '02468abc';
var e = e||window.event;
var k = e.keyCode||e.which;
var r = allowed.indexOf(String.fromCharCode(k))!=-1;
r = (k==8||(k>=35&&k<=40)||k==46)?true:r;
if(!r) {
e.returnValue = false;
if(e.preventDefault)
e.preventDefault();
}
});
});
Add the characters you want to pass inside the variable allowed, in this code, allowed characters are 0, 2, 4, 6, 8, a, b, and c.
Just make sure you have this in your HTML:
<input id="input" type="text"/>
You should be good to go using this.
If jQuery is not an option, leave a comment and I'll add some jQuery-less code.
Edit: Changed code to allow use of arrow keys, backspace, home, end, and delete.
Rou's code is clean, but keycode will always return capital letters. If you need this to be case-sensitive, keycode won't work.
I'm also assuming you always want to check the last character entered.
function check(e,element) {
var acceptable = 'abcd12';
var char = element.value.charAt(element.value.length - 1);
if(acceptable.indexOf(char)>=0){
document.getElementById("result").innerHTML="true";
}
else
{
document.getElementById("result").innerHTML="false";
}
}
var inputElement = document.getElementById('someId');
inputElement.addEventListener('keyup', function( e ) {
check( e, inputElement )
});
Here's the code in JSFiddle if you want to modify it: http://jsfiddle.net/hckytaez/4/
I'm using the following function to remove non-digit characters from input fields onkeyup (as posted in numerous places). The function works fine for text inputs but when linked to a number input, the number input is completely erased when a non-digit character is typed.
Thoughts?
function RemoveNonNumeric(e)
{
var el = e.target;
el.value = el.value.replace(/\D/g,"");
return;
}//end RemoveNonNumeric
What happens is as soon as there is a non-numeric character in a number input field... the value becomes empty. One way to solve this would be to save the last true numeric value and replace the current value with that if it becomes an empty value. Seems kind of hacky, but see if it works for you:
JSFiddle
var lastNumericValue = 0;
function RemoveNonNumeric(e)
{
if(e.keyCode === 8)
return;
var el = e.target;
if(el.value === "") {
el.value = lastNumericValue;
} else {
lastNumericValue = el.value;
}
}
on second thought... how about preventing the non-numeric values from ever being placed instead of removing them after the fact? Run the following onkeypress
JSFiddle
function RemoveNonNumeric(e) {
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
};
If you debug, you will find that when the value of a number input is invalid, el.value returns an empty string. I am unaware of a workaround.
I called a class called test for my textbox. When I entered the first value for e.g. the first value as 4., then suddenly the output coming as 4.00. I just want to restrict entry only for two decimal places.
$(".test").keyup(function (event) {
debugger;
this.value = parseFloat(this.value).toFixed(2);
});
This small change to your code may suffice:
this.value = this.value.replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2');
Essentially replace the decimal point followed by any number of digits by a decimal point and the first two digits only. Or if a non digit is entered removes it.
What about something like this:
$(".test").keyup(function (event) {
if ((pointPos = this.value.indexOf('.')) >= 0)
$(this).attr("maxLength", pointPos+3);
else
$(this).removeAttr("maxLength");
});
Here is a working fiddle.
you can use the maxLength attribute for that, try
$(".test").keyup(function (event) {
var last = $(this).val()[$(this).val().length - 1];
if (last == '.') {
$(".test").attr("maxlength", $(this).val().length+2);
}
});
You shouldn't worry about what the user has in the input until they submit the form. You really don't care what's in there before then. However, if you want to warn about invalid input, you can put a message on the screen if you detect non–conforming input, e.g.
<script>
function validate(element) {
var re = /^\s*\d*\.?\d{0,2}\s*$/;
var errMsg = "Number must have a maximum of 2 decimal places";
var errNode = document.getElementById(element.name + '-error')
if (errNode) {
errNode.innerHTML = re.test(element.value)? '' : errMsg;
}
}
</script>
You should probably also put a listener on the change handler too to account for values that get there by other means.
$(document).on("keyup", ".ctc", function ()
{
if (!this.value.match(/^\s*\d*\.?\d{0,2}\s*$/) && this.value != "") {
this.value = "";
this.focus();
alert("Please Enter only alphabets in text");
}
});
I;m trying yo implement a javacript function which will not allow to the user to input anything else than float numbers (digits)
This is my approach but I don't know how to improve it in order to allow submition of negatives numbers also (allow '-' key) and work on IE also.
function digits_only(evt, form) {
var evt = evt || window.event,
targ = evt.target || evt.srcElement,
charCode = evt.which || evt.keyCode,
keyChar = String.fromCharCode(charCode),
isValid = true;
if (charCode > 13) {
isValid = /[0-9.]/.test(keyChar);
//if a dolt is already in input
if (keyChar === '.' && /\./.test(targ.value)) {
isValid = false;
}
}
return isValid;
}
I think you are looking for so called "input masks". They are a lot more powerful then just allowing numbers. But you can surly use them for that. Google "javascript input mask" or check out this jQuery Plugin.
EDIT:
Seems like the linked plugin only supports fixed length masks, but the term may be a good starting point...
Is this on an ASP.NET web application? You could use the AjaxControlToolkits MaskEditExtender.
I have asking similar question here:
restrict user input using javascript
but no one give the exact answer for the problem, so let's wait until WebForms 2.0 released
You can subscribe to "InputEvent" and then get "data" prop. For example
input.addEventListener('beforeinput', (event) => {
const data = event.data;
// if "data" is present - user enter some character
// if "data" is NOT present - user tap non character key (e.g. delete, shift and other)
if(data) {
// check if data is number or "."
const isAllow = /\d|\./.test(data);
if(!isAllow) {
e.preventDefault();
}
}
})
More info
event.data - https://developer.mozilla.org/en-US/docs/Web/API/InputEvent/data
beforeinput event - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/beforeinput_event