How do i prevent dead keys to be displayed in a input - javascript

Recently i made an input script where you can only write numbers and have a total length of 5. But some keys of code "Dead" still appear when pressed.How do i prevent the key to even show in the input box?
Here is the function to make it only numeric:
public restrictNumeric(e) {
if (e.which) {
let input = String.fromCharCode(e.which);
if (e.which == "Dead") {
console.log("Test")
}
return /[\d]/.test(input);
}
return false
}
Here is the Html:
<input matInput placeholder="Ex. 447" formControlName="NumTag" type="number"
onKeyPress="if(this.value.length==5) return false;"
(keydown)="restrictNumeric($event)">

Related

show alert when value is number

I need to show the alert box when the user typed the number in the input field
<input type="text" class="only-text">
if (document.querySelector('.only-text').value === '') {alert('no numbers are allowed!')};
I'd use the beforeinput event, this way you can check the value inserted before it is painted in the DOM, and if it's not good you can prevent it from being painted.
function isBeforeInputEventAvailable() {
return window.InputEvent && typeof InputEvent.prototype.getTargetRanges === "function";
}
if (isBeforeInputEventAvailable()) onlyText.addEventListener("beforeinput", e => {
if (/[\d]+/.test(e.data)) {
alert('no numbers are allowed!')
e.preventDefault()
};
})
<input type="text" id="onlyText">

I want to add an alert in the if else statement. How do I do that?

I want to add an alert inside the if and else if. If the user does not enter anything in the prompt box the alert triggers. Also if the user enters a number the prompt it will say that the user entered a number. How do do that?
let myForm2 = document.querySelector('.form2');
let pDisplay1 = document.querySelector('.display4');
myForm2.addEventListener('submit', function(e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname == null) {
} else if (isNaN(uname) == false) {
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
})
<p> Activity 6</p>
<form class="form2" method="get">
<label>Full Name: <input type="text" class="inputName2"></label>
<input type="submit">
</form>
<p class="display4"></p>
document.querySelector('.className').value will return a string.
string.trim() removes the whitespaces and if the length === 0 it means that the input is empty or has only whitespaces which you generally want to treat as empty. If you consider space is a valid input you don't have to use trim().
The + sign will convert a string into a number otherwise you could use parseInt(variable).
Number.isInteger(variable) will return true if the variable is an integer.
You could also write !isNaN(+uname) or +uname !== Number.NaN
myForm2.addEventListener('submit', function (e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname.trim().length === 0) {
alert('You should write something');
} else if (Number.isInteger(+uname)) {
alert('You wrote a number');
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
});
Empty string is not equal to null, replace uname==null with uname=='', after the replacement, you can identify the situation that the user did not input, if it is more strict, you can also use trim to remove whitespace and then do condition review

Form Validation Vanilla JS

I'm building a multipage form and I have some unusual validation requirements. Here's what I'd like to do/what I have done so far.
What I Want to Do:
(1) As each form field is filled in, I want a function to run and check that the user-input has met certain conditions -- i.e. for first and last name, that there are no numbers and there is a space in between the names.
(2) Once each of the field are full and have passed as true, I want another function to run that re-enabled a previously disabled "Next" button that will move the user to the next page of the form.
What I Have Done
(1) Created a mini version of the form with two inputs:
One that takes a first name, a space and a last name
One that takes a phone number set up the following way xxx xxx xxx
(2) I've console.logged the results with pass/fail logic so I know when certain things are being input by the user, that the code is validating properly.
Where I am Stuck:
I do not know how to create the secondary code that will reenabled the previously disabled "next" button that will move the form to the next page.
What I would like to do is make it so when the "Next" button is reenabled, and clicked on, it's own onclick function hides the current page, looks for the next page in the sequence and changes its display:block and I believe I have that code worked out separately, but I don't know how to integrate it with my other needs.
function checkForm()
{
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
function checkFirstName()
{
if(firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
console.log("Put a first Name and Last Name");
}
else
{
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber()
{
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/))
{
console.log("Please Put in a proper phone number");
}
else
{
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
};
<form>
First Name: <input type="text" id="name" onblur="checkForm()" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" onblur="checkForm()" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
See below code.
It might be more user-friendly to use on keyup rather than onblur, as most users I know will try and click the disabled button, rather than pressing tab or focusing on another element.
function checkForm() {
var firstName = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var phoneCanSubmit, nameCanSubmit = false;
function checkFirstName() {
if (firstName == "" || !isNaN(firstName) || !firstName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
nameCanSubmit = false;
console.log("Put a first Name and Last Name");
} else {
nameCanSubmit = true;
console.log("Thank You");
}
};
checkFirstName();
function checkPhoneNumber() {
if (!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
phoneCanSubmit = false;
console.log("Please Put in a proper phone number");
} else {
phoneCanSubmit = true;
console.log("Thank you");
cansubmit = true;
}
};
checkPhoneNumber();
if (nameCanSubmit && phoneCanSubmit) {
document.getElementById("myButton").disabled = false;
} else {
document.getElementById("myButton").disabled = true;
}
};
<form>
First Name:
<input type="text" id="name" onblur="checkForm()" />
<label id="nameErrorPrompt"></label>
<br />Phone Number:
<input type="text" id="phone" onblur="checkForm()" />
<label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
The code below gives you what you want. I removed some extraneous checks to simplify the code and also moved the event handlers from he HTML to the JavaScript. I also pulled the field checks out of the larger checkForm function. This provides you the flexibility to use them one at at time if need be.
window.addEventListener('load', function(e) {
var nameInput = document.getElementById('name');
var phoneInput = document.getElementById('phone');
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', function(e) {
e.preventDefault(); //Stop the page from refreshing
getNextPage('Next page shown!!');
}, false);
nameInput.addEventListener('blur', function(e) {
checkName(this.value);
}, false);
phoneInput.addEventListener('blur', function(e) {
//Uncomment below to make this responsible only for checking the phone input
//checkPhoneNumber(this.value);
/*You could do away with diasbling and check the form
on submit, but if you want to keep the disable logic
check the whole form on the blur of the last item*/
checkForm();
}, false);
}, false);
function getNextPage(foo) {
console.log('Callback fired: ', foo);
//Do something here
}
function checkPhoneNumber(phone) {
if(!phone.match(/^[0-9]*\s{1}[0-9]*\s{1}[0-9]*$/)) {
console.log("Please Put in a proper phone number");
return 0;
}
else {
console.log("Thank you name entered");
return 1;
}
};
//Removed a bit of over coding, no ned to check isNaN or empty string since using regex already
function checkName(firstAndLastName) {
if(!firstAndLastName.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
console.log("Put a first Name and Last Name");
return 0;
}
else {
console.log("Thank You phone entered");
return 1;
}
};
function checkForm() {
var validCount = 0;
fieldCount = document.forms[0].elements.length - 1; //substract one for the submitbutton!
var phoneNum = document.getElementById('phone').value;
var name = document.getElementById('name').value;
var myButton = document.getElementById('myButton');
validCount += checkPhoneNumber(phoneNum);
validCount += checkName(name);
console.log(validCount + ' of ' + fieldCount + ' fields are valid');
if (validCount > 0 && validCount === fieldCount) {//Compare the inputs to the number of valid inputs
myButton.disabled = false;
}
else {
myButton.disabled = true;
}
}
HTML
<form>
First Name: <input type="text" id="name" /><label id="nameErrorPrompt"></label>
<br />
Phone Number: <input type="text" id="phone" /><label></label>
<br />
<button id="myButton" disabled="disabled">Test Me</button>
</form>
How about you start by making the onblur for each input return a boolean indicating if the field is valid.
Then setting a cansubmit variable (= checkName && checkPhone) in the checkForm function and only moving on after that - then you don't need to enable and disable the button.
If you really want the button to enable you can use the same pattern, but do
document.getElementById("myButton").disabled = !canSubmit;
and you will always want to call checkForm on field blur like you are now.
Also note you aren't scoping canSubmit locally right now.

Want to prevent a textbox from becoming empty with javascript

So i already have a textbox in which you can only enter numbers and they have to be within a certain range.The textbox defaults to 1,and i want to stop the user from being able to make it blank.Any ideas guys?Cheers
<SCRIPT language=Javascript>
window.addEventListener("load", function () {
document.getElementById("quantity").addEventListener("keyup", function (evt) {
var target = evt.target;
target.value = target.value.replace(/[^\d]/, "");
if (parseInt(target.value, 10) > <%=dvd5.getQuantityInStock()%>) {
target.value = target.value.slice(0, target.value.length - 1);
}
}, false);
});
<form action="RegServlet" method="post"><p>Enter quantity you would like to purchase :
<input name="quantity" id="quantity" size=15 type="text" value="1" />
You could use your onkeyup listener to check if the input's value is empty. Something along the lines of:
if(target.value == null || target.value === "")
target.value = 1;
}
You could add a function to validate the form when the text box loses focus. I ported the following code at http://forums.asp.net/t/1660697.aspx/1, but it hasn't been tested:
document.getELementById("quantity").onblur = function validate() {
if (document.getElementById("quantity").value == "") {
alert("Quantity can not be blank");
document.getElementById("quantity").focus();
return false;
}
return true;
}
save the text when keydown
check empty when keyup, if empty, restore the saved text, otherwise update the saved text.
And you could try the new type="number" to enforce only number input
See this jsfiddle

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">

Categories

Resources