Html and javascript input validation - javascript

I am trying to have my input only accept Numbers and the '.', it is working great but it doesn't allow for number pad number keys. I cant seem to find the exact answer online.
HTML
<input type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#" onkeypress="return isNumeric(event)" onkeydown="return keyispressed(event);">
JavaScript
//prevent , and $ from being input
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval) && (e.which != 8 ) && (e.which != 190 )){
return false;
}
return true;
}
//is input numeric
function isNumeric (evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode (key);
var regex = /[0-9]|\./;
if ( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Thanks for the help!

The best way I believe would be to add a class to all the inputs that only allow numbers. Then you can restrict any input that doesn't match the pattern or a number/decimal.
function numberVerfication(value) {
var pattern=/^[0-9]*(\.)?[0-9]*$/;
if (value.match(pattern) != null){
return value
}
else {
var p=/[0-9]*(\.)?[0-9]*/;
return value.match(p)[0];
}
}
$('.numbersOnly').keyup(function(e) {
e.target.value = numberVerfication(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='numbersOnly' type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#">

Simple using REGEXP
HTML
<input type="text" class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct">
JQUERY
$('.numbersOnly').keyup(function (e) {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
JAVA SCRIPT
function numValidate(that){
that.value = that.value.replace(/[^0-9\.]/g, '');
}
<input type="text" onkeypress='numValidate(this)' onkeyup='numValidate(this)' class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct"/>
Demo

function numberVerfication(value){
return value.replace(/[^0-9.\-+]/g, '');
}
$('.numbersOnly').keyup(function(e){
e.target.value=numberVerfication(e.target.value);
});

Related

How prevent whitespace in input field with plain javascript

I have an username input field and trying to prevent user fill them with white spaces.
<input type="text" name="username" />
i do this and whitespace isn't blocked
var
field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var
key = event.keyCode;
return (key !== 32);
});
Use event.preventDefault to prevent its default behavior.
var field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var key = event.keyCode;
if (key === 32) {
event.preventDefault();
}
});
<input type="text" name="username" />
If you want to use the return false;, then you should use the onkeypress of the input instead, jsfiddle
field.onkeypress = function(e) {
var key = e.keyCode;
return (key !== 32);
};
Modify the input like:
<input type="text" name="username" onkeypress="CheckSpace(event)"/>
Then the javascript is:
<script type="text/javascript">
function CheckSpace(event)
{
if(event.which ==32)
{
event.preventDefault();
return false;
}
}
Try checking for all the different kinds of whitespaces listed here Are there other whitespace codes like &nbsp for half-spaces, em-spaces, en-spaces etc useful in HTML?
So you code would be:
var field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var
key = event.keyCode;
return (key !== 32 && key !== 160 && key != 5760 && key != 8192 && key != 8192 && key != 8194 && key != 8195 && key != 8196 && key != 8197 && key != 8198 && key != 8199 && key != 8200 && key != 8201 && key != 8202 && key != 8232 && key != 8233 && key != 8239 && key != 8287 && key != 12288);
});
Here is the complete list of all the different kinds of whitespaces: https://en.wikipedia.org/wiki/Whitespace_character#Spaces_in_Unicode
In case anyone needs this to be done which will replace all whitespace automatically and will not allow user to put space and will force them to put username without space even then copy paste . Here is the code.
<script type="text/javascript">
var field = document.querySelector('[name="username"]');
field.addEventListener('keyup', function ( event ) {
var userName = field.value;
userName = userName.replace(/\s/g, '');
field.value = userName;
});
</script>
HTML only solution using the pattern attribute and regex.
<form>
<input type="text" name="username" pattern="[^\s]+">
<button type="submit">Submit</button>
</form>
const key = e.keyCode
const keyCodes = [
32, 160, 5760, 8192, 8192, 8194, 8195, 8196, 8197, 8198, 8199,
8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288,
]
if (keyCodes.some((val) => val === key)) {
e.preventDefault()
}
here is a simple solution !
Hey i have simple solution regarding your question try one
If you want to submit only text and whitespace than use this one
<input type="text" name="Name" required pattern="[a-zA-Z ]+" >
If you want to submit number and whitespace than use this one
<input type="text" name="Name" required pattern="[0-9 ]+" >
If you want to insert text not whitespace than use this one
<input type="text" name="Name" required pattern="[a-zA-Z]+" >
Use any line according to your requirements no extra line of code or condition simple and secure

How to change the value of an active text input using Javascript?

I am trying to make a form with a date input.
However, this input is in date format, and I would like to change the value while the control is still active.
Here is the full code :
// Javascript code
function add_value()
{
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length = 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length = 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onchange="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
But this is only updating the text when you exit of the control, and I would like to know how to run this javascript function while the control is still active.
Thanks.
You need to use onkeyup.
<input id="fin_mater" type="text" onkeyup="add_value();" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
From the docs
Execute a JavaScript when a user releases a key
Also in your if your are using =, you should be using ==
...
if(document.getElementById("fin_mater").value.length == 2)//==
...
else if(document.getElementById("fin_mater").value.length == 5)
...
First let's make the code smell more like the "javascript" :)
// Javascript code
function $(id) {
return document.getElementById(id);
}
function add_value(event) {
var dataOriginale = $("fin_mater").value,
len = dataOriginale.length,
key = event.keyCode || event.charCode;
// Allow BACKSPACE and DEL
if (key === 8 || key === 46) {
return true;
}
if(len === 2 || len === 5) {
$("fin_mater").value = dataOriginale + '-';
}
return false;
}
<!-- Code of the input -->
<input id="fin_mater" type="text" onKeyUp="add_value(event);" name="fin_mater" maxlength="10" placeholder="DD-MM-YYYY"/>
If you want to append the "-" automatically when you input numbers, you can listen on the "onKeyUp" event of the text box rather than the "onchange".
PS: You can use the key code to limit only numbers input and also do some validations.
You can use keypress():
$(document).ready(function()
{
$( "#fin_mater" ).keypress(function() {
var dataoriginale = document.getElementById("fin_mater").value;
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
});
});
Fiddle
With some of your help and some documentation, I finally went to this, that works perfectly on every browser that supports javascript.
$(document).ready(function(event)
{
$( "#fin_mater" ).keypress(function(event) {
var dataoriginale = document.getElementById("fin_mater").value;
if(event.keyCode != 8)
{
if(document.getElementById("fin_mater").value.length == 2)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
else if(document.getElementById("fin_mater").value.length == 5)
{
document.getElementById("fin_mater").value=dataoriginale+'-';
}
}
});
});
Thanks everyone !

Html input validation [duplicate]

Ok basically when I type , it won't allow it.
I want to add more like < > / \ etc how do I do it?
$("#in1").keypress(function (evt) {
if (String.fromCharCode(evt.which) == ",")
return false;
});
<input type="text" id="in1">
Can see the demo here. http://jsfiddle.net/QshDd/38/
If you have a list of disallowed characters, you can forbid them in this fashion:
$("#in1").keypress(function (evt) {
return [',', '<', '>', ].indexOf(String.fromCharCode(evt.which)) === -1;
});
its working , you Required to give more conditions:
$("#in1").keypress(function (evt) {
if (String.fromCharCode(evt.which) == ",")
return false;
if (String.fromCharCode(evt.which) == "<")
return false;
if (String.fromCharCode(evt.which) == ">")
return false;
if (String.fromCharCode(evt.which) == "\\")
return false;
});
Another Solution , either use regEx or use XMLParser or JSON parser methods.
if you want something like this
<input type="text"> ===> input typetext
$("#in1").keypress(function (evt) {
if (isValid(String.fromCharCode(evt.which)))
return false;
});
function isValid(str){
return /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
http://jsfiddle.net/QshDd/61/
Try this, if you need only alphabets
$("#in1").keypress(function (evt) {
var expr = /^([a-zA-Z\s]+)$/i;
if (!String.fromCharCode(evt.which).match(expr))
return false;
});
var chars = new Array("<", ">" ,"/" ,"\\");
$("#in1").keypress(function (evt) {
if(!(chars.indexOf(String.fromCharCode(evt.which)) > -1))
return false;
});

Javascript - validation, numbers only

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
Part of the Login
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
Edit:
RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.
Simply omit the negating ! and use if(/\D/.test(z)).
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
Validate numbers in JavaScript - IsNumeric()
function validateNumber(e) {
const pattern = /^[0-9]$/;
return pattern.test(e.key )
}
<input name="username" id="username" onkeypress="return validateNumber(event)">
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
Javascript Approach
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery Approach
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
The above answers are for most common use case - validating input as a number.
But to allow few special cases like
negative numbers & showing the invalid keystrokes to user before
removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
Using the form you already have:
var input = document.querySelector('form[name=myForm] #username');
input.onkeyup = function() {
var patterns = /[^0-9]/g;
var caretPos = this.selectionStart;
this.value = input.value.replace(patterns, '');
this.setSelectionRange(caretPos, caretPos);
}
This will delete all non-digits after the key is released.
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
elem[i].addEventListener('keypress', function(event){
var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
var validIndex = keys.indexOf(event.charCode);
if(validIndex == -1){
event.preventDefault();
}
});
}
If you are using React, just do:
<input
value={this.state.input}
placeholder="Enter a number"
onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
state = {
input: '',
}
onChange = e => {
let input = e.target.value.replace(/[^0-9]/g, '');
this.setState({ input });
}
render() {
return (
<div>
<input
value={this.state.input}
placeholder="Enter a number"
onChange={this.onChange}
/>
<br />
<h1>{this.state.input}</h1>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
</script>
// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:
$(document).ready(function () {
$(".nosonly").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// 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) {
alert("Only Numbers Allowed"),event.preventDefault();
}
}
});
});
Avoid symbols like "." "," "+" "-". I tried it and it works fine.
$('#example').keypress(function (evt) {
if (evt != null && evt.originalEvent != null && /\D/.test(evt.originalEvent.key)) {
evt.preventDefault();
evt.stopImmediatePropagation();
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="example" id="example">

How to prevent invalid characters from being typed into input fields

Onkeydown, I run the following JavaScript:
function ThisOnKeyDown(el) {
if (el.title == 'textonly') {
!(/^[A-Za-zÑñ-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ-\s]/ig, '') : null;
}
if (el.title == 'numbersonly') {
!(/^[0-9]*$/i).test(el.value) ? el.value = el.value.replace(/[^0-9]/ig, '') : null;
}
if (el.title == 'textandnumbers') {
!(/^[A-Za-zÑñ0-9-\s]*$/i).test(el.value) ? el.value = el.value.replace(/[^A-Za-zÑñ0-9-\s]/ig, '') : null;
}
}
One of these three title attributes is given to various input fields on the page. The code works so far as invalid characters are correctly erased, but not until the next character is entered. I want to find a way to simply deny the invalid input in the first place. I appreciate your help!
Edit: I create the events globally. Here's how I do that:
function Globalization() {
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
inputs[i].onfocus = createEventHandler(
ThisOnFocus, inputs[i]);
inputs[i].onblur = createEventHandler(
ThisOnBlur, inputs[i]);
inputs[i].onkeydown = createEventHandler(
ThisOnKeyDown, inputs[i]);
inputs[i].onkeyup = createEventHandler(
ThisOnKeyUp, inputs[i]);
}
}
Globalization() is run body.onload
Therefore, a typical input field has HTML without function calls like this:
<input id="AppFirstName" style="width: 150px;" type="text" maxlength="30" title="textonly"/>
To prevent it from being set in the first place, you can return false on the keydown event handler, thus preventing the event from propagating any further.
I wrote the example below using jQuery, but you can use the same function when binding traditionally.
Though it's important to validate on the server-side as well, client-side validation is important for the sake of user friendliness.
$("input.number-only").bind({
keydown: function(e) {
if (e.shiftKey === true ) {
if (e.which == 9) {
return true;
}
return false;
}
if (e.which > 57) {
return false;
}
if (e.which==32) {
return false;
}
return true;
}
});
The above code does it says- allows ONLY numbers. You can modify it by adding exception to say BACKSPACE for example like this
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function keyispressed(e){
var charValue= String.fromCharCode(e.keyCode);
if((isNaN(charValue)) && (e.which != 8 )){ // BSP KB code is 8
e.preventDefault();
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeydown="return keyispressed(event);"/>
</body>
</html>
$('.key-filter').keypress(function () {
if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();
});
then add the key-filter class to your input if using jquery
or
<input type="text" onkeypress="if (event.key.replace(/[^\w\-.]/g,'')=='') event.preventDefault();" />
just put the charaters you want to allow inside the [] after the ^.
this allows all letters numbers _ - and .
You can replace your input value during the "input" event :
// <input oninput=onInput(event) />
const onInput = event => {
event.target.value = event.target.value.replace(/[^0-9+]/g, '')
}
source : https://knplabs.com/en/blog/how2-tips-how-to-restrict-allowed-characters-inside-a-text-input-in-one-line-of-code
i found this solution in: http://help.dottoro.com/ljlkwans.php
works as intended.
<script type="text/javascript">
function FilterInput (event) {
var keyCode = ('which' in event) ? event.which : event.keyCode;
isNumeric = (keyCode >= 48 /* KeyboardEvent.DOM_VK_0 */ && keyCode <= 57 /* KeyboardEvent.DOM_VK_9 */) ||
(keyCode >= 96 /* KeyboardEvent.DOM_VK_NUMPAD0 */ && keyCode <= 105 /* KeyboardEvent.DOM_VK_NUMPAD9 */);
modifiers = (event.altKey || event.ctrlKey || event.shiftKey);
return !isNumeric || modifiers;
}
</script>
< body>
The following text field does not accept numeric input:
<input type="text" onkeydown="return FilterInput (event)" />< /body>
it allows text and !"#$%& but you can adjust it adding these to the validationto only allow numbers by removing the ! in the return
Code is useful for preventing user from typing any other character except number.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval)){
return false;
}
return true;
}
</script>
</head>
<body>
<input type="text" onkeydown="return keyispressed(event);"/>
</body>
</html>
You could easily do this in a single html line.
Like this to disallow spaces:
<input type="text" onkeypress="return event.charCode != 32">
Or this to only allow numbers:
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
Just look up the unicode of any numbers you want to allow or disallow.
Run your code against the onkeyup event and not the onkeydown event. This way you can access the result of the very last keystroke where as the onkeyup event executes as a key is pressed without knowing its result.

Categories

Resources