how to restrict input type - javascript

Currently I'm trying to restrict input data which can only input 3 letters and 2 numbers. It will be checked after onclicked button. My incorrect code:
component.html
<input type="text" name="test3" [(ngModel)]="test3"
onkeyup="this.value=this.value.replace(/[^\a-\z\A-\Z0-9]/g,'');">
<button (click)="checkNumber3(test3)">submit</button>
component.ts
checkNumber3(test3): void {
console.log(test3);
if (test3 !== test3.match(/([a-z])+/) * 2 || test3 !== test3.match(/([A-Z])+/) * 2
&& test3 !== test3.match(/([0-9])+/) * 3
) {
alert('only can input 2 letters plus 3 numbers');
} else {
alert('correct');
}
}
Thanks for your help!

I think you should do somethig like:
if(test3.match(/([a-z])+/).length === 2 ||
test3.match(/([A-Z])+/).length === 2 &&
test3.match(/([0-9])+/).length === 3)
{
doStuff()
}
EDIT (Explaination)
String.match returns an array of matches. So getting its length will let you know if you have correct data.
Also, the correct regex is /([a-z]])/g and analagically for A-Z and 0-9

Rather than running multiple RegExes over the same string and creating throw-away arrays. you should be able to make a simple validate functions with a single regex and test(). For example:
function validate(string) {
// two letters or three numbers
return /^([a-zA-Z]{2}|[0-9]{3})$/.test(string)
}
console.log(validate("Aa")) // true
console.log(validate("Aaa")) // false
console.log(validate("120")) // true
console.log(validate("1090")) // false
console.log(validate("1")) // false
console.log(validate("")) // false
console.log(validate("A3")) // false

Your Javascript block needed some changes. Give this a shot:
if (test3.match(/([A-z])/g).length === 2 && (test3.match(/([0-9])/g).length === 3)) {
alert('correct');
} else {
alert('only can input 2 letters plus 3 numbers');
}

Use [maxlength] and [minlength] is component.html file for checking the length.
and for checking number and letter in the ts file, use ^\d{2}[a-zA-Z]{3}$ this regex.

You should use split() and filter() like so:
checkNumber3(test3): void {
console.log(test3);
if (test3.split("").filter(e => isNaN(e)).length > 2 || test3.split("").filter(e => typeof parseInt(e) == "number")) {
alert('only can input 2 letters plus 3 numbers');
} else {
alert('correct');
}
}

you can do it like this!
<head>
<script type="text/javascript">
function checkIf_AlphaNum()
{
var regex1 = RegExp('^([a-zA-Z]){3}([0-9]){2}?$');
if(regex1.test(document.getElementById("txtnumber").value))
{
document.getElementById("msg_2_show").innerHTML="given string matched against pattern!";
document.getElementById("msg_2_show").style.color="#7CFC00";
//alert("given string matched against pattern!");
}
else {
document.getElementById("msg_2_show").innerHTML="invalid pattern!";
document.getElementById("msg_2_show").style.color="#B22222";
}
}
</script>
</head>
<body>
<h4 id="msg_2_show"></h4>
<form >
<label>Enter No.:</label>
<input type="text" id="txtnumber" name="txtnumber" />
<input type="button" value="Submit!" name="btnsubmit" onclick="checkIf_AlphaNum()"/>
</form>
</body>
</html>

add your checknumber function like below code inside input keypress
<input type="text" name="test3" [(ngModel)]="test3" (keypress)="checkNumber3(test3)"
onkeyup="this.value=this.value.replace(/[^\a-\z\A-\Z0-9]/g,'');">
<button (click)="checkNumber3(test3)">submit</button>

Check it from here for Angular 6 online editor :
StackBlitz

Related

jQuery Greater than and Smaller than check

This is my form:
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
And this my jQuery that's not working:
$('.fms-quote-form').submit(function() {
if ( $('#fms-zip').val() >= 90000 AND <=96162 ) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
How do I (i) check that the value of #fms-zip is greater than 90000 and smaller than 96162 to submit the form, and (ii) redirect the user to another website if any other value is entered?
Look forward to your input :)
Always check the error console - you're assuming syntax that is faulty. AND will be throwing an error - you need &&.
What's more, you can't just specify your higher number and assume JavaScript will know to compare it against the same subject value you compared the lower value against - you have to repeat the subject.
let val = parseInt($('#fms-zip').val());
if (val >= 90000 && val <= 96162 ) { //<-- note 2 references to #val
As #Alessio Cantarella points out, you also need to cast the value to a number - reading the field's value returns a string.
To check if ZIP is greater than 90000 and smaller than 96162, you need to use:
parseInt function to convert #fms-zip's value to an integer
&& logic operator to check that both conditions are valid.
$(function() {
$('.fms-quote-form').submit(function() {
let zip = parseInt($('#fms-zip').val());
let isZipValid = zip >= 90000 && zip <= 96162;
if (isZipValid) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
You can try like this -
$(function() {
$('.fms-quote-form').submit(function() {
var valueZip= parseInt($('#fms-zip').val());
if (valueZip >= 90000 && valueZip <= 96162) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});

Allow space in textbox only if any existing characters or number in that

I have textbox in which I need validation in such way that it should not allow spaces if textbox is empty. If any values are there in textbox then only it should allow spaces. I am trying below code but not working
var letters = /^[0-9a-zA-Z]+$/;
$("#input1").on("blur ", function() {
function alphanumeric(username) {
if (username.value.match(letters)) {
return true;
} else {
$('#input1').on('keypress', function(e) {
if (e.which == 32)
return false;
});
return false;
}
}
})
if you are using form, you do not need any javascript
<form action='/'>
<input pattern="\s*\S+.*" title="space only is not allowed" required/>
<input type="submit">
</form>
why not just trim?
username.trim()
after that you can just return the result of match.
Add a function on your blur event that will trim the values which will remove preceding and succeeding whitespace. If the value is empty it will result in '' .
$("#input1").on("blur", function () {
if($(this).val().trim() === ''){
alert('empty value');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input1' />
Your Regex seems wrong.
You're not allowing spaces characters.
Try this one instead: /\S/
\S is any non whitespace character.
If you want to start by a character, it will become /^\S/.
^ is when you want to start by the following character
$ is when you want to finish by the previous character
You can do it like this:
$(function() {
$('#input1').on('keypress', function(e) {
if ($(this).val() == "")
if (e.which == 32)
return false;
});
});
Online Demo (jsFiddle)

How can I use JQuery to add a decimal and trailing zeros to currency?

I have checked all related questions and none, fully address my question. I know how to convert to money with symbols and commas, but not sure how to add trailing zeros if the user did not specify cents.
I did come across a post that mentioned adding this .toFixed(2) but I do not understand how to incorporate that into my function.
Desired function is 14578 to convert to $14,578.00 but do not add the zeros if the number were 14578.79 to $14,578.79. Also I noticed that it puts a dollar sign in the field even if left blank. Any way to avoid that?
$('.money').blur(function(e){
$(this).val(formatCurrency(this.value.replace(/[,$]/g,'')));
}).on('keypress',function(e){
if(!$.isNumeric(String.fromCharCode(e.which))) e.preventDefault();
}).on('paste', function(e){
var cb = e.originalEvent.clipboardData || window.clipboardData;
if(!$.isNumeric(cb.getData('text'))) e.preventDefault();
});
function formatCurrency(number){
var n = number.split('').reverse().join("");
var n2 = n.replace(/\d\d\d(?!$)/g, "$&,");
return '$' + n2.split('').reverse().join('');
}
input {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class="money"/>
<input type='text'/>
<input type='text' class="money"/>
<input type='text'/>
<input type='text' class="money"/>
<input type='text'/>
<input type='text' class="money"/>
<input type='text'/>
Thank you!
To prevent inserting empty "$" you need to check if number is empty and return the function. Here's a solution for you. You also need to allow "." in your keypress to allow users to add cents.
$('.money').blur(function(e){
if($(this).val() == "") return;
$(this).val(formatCurrency(this.value.replace(/[,$]/g,'')));
}).on('keypress',function(e){
if(String.fromCharCode(e.which) != "." && !$.isNumeric(String.fromCharCode(e.which))) e.preventDefault();
}).on('paste', function(e){
var cb = e.originalEvent.clipboardData || window.clipboardData;
if(!$.isNumeric(cb.getData('text'))) e.preventDefault();
});
function formatCurrency(number){
if(number == "") return;
number = parseFloat(number).toFixed(2);
var n = number.split('').reverse().join("");
console.log(n);
var n2 = n.replace(/\d\d\d(?!$)/g, "$&,");
return '$' + n2.split('').reverse().join('');
}
Check jsFiddle here: https://jsfiddle.net/7scapsk9/
parseFloat(value).toFixed(n)
Where value is your number (can be string) and n is the number of decimals to show
Replace your current formatCurrency function with this one:
function formatCurrency(number) {
return (number != null && number != "") ? "$".concat(parseFloat(number).toFixed(2).toString()
.split('').reverse().join("")
.replace(/\d\d\d(?!$)/g, "$&,")
.split('').reverse().join("")) : number;
}
If the number (or string that's a number) that's passed in isn't null, undefined, or an empty string it will parse the number into valid currency.

Check if value entered is a valid integer

I want to check if the value entered by the user is a valid integer using jquery
I have tried this code but it always seems to return true:
if ((manageridEntered === "") || ($.isNumeric(manageridEntered))) {
success = false;
}
You could use classic JavaScript :
var isNumber = Number.isInteger(yournumber);
Or if you want to check if it isn't (without using !) :
var isNaN = Number.isNaN(yournumber);
console.log(Number.isInteger(0.1)); // false
console.log(Number.isInteger(1)); // true
console.log(Number.isInteger(-100000)); // true
console.log(Number.isInteger(Math.PI)); // false
console.log(Number.isInteger(-Infinity)); // false
console.log(Number.isInteger(true)); // false
console.log(Number.isInteger(NaN)); // false
console.log(Number.isInteger(0)); // true
console.log(Number.isInteger("10")); // false
No need to use jquery
You can use javascript isNaN()
isNaN() accepts decimal numbers also
return !isNaN(manageridEntered))
or
You can use plain javascript regex here to match only digits
return new RegExp('^\\d+$').test(manageridEntered))
You can use vanilla JavaScript:
success = !manageridEntered.length || parseInt(manageridEntered) == manageridEntered;
Use regex
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
}
Example taken from checking if number entered is a digit in jquery
$('.submitBtn').click(function() {
var Number = $('#Number').val();
if ((Number === "") || ($.isNumeric(Number))) {
alert('Valid NUmber');
}else{
alert('Not Valid NUmber');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="post" action="">
Inateger Value: <input type="text" name="Number" id="Number" />
<input type="submit" value="Submit" class="submitBtn">
</form>
isNumeric is checking for a number (which could be wrapped in a string too), not an integer. Beside that isNumeric() is not always returning true like you can see in the following snippet using JQuery 2.1.1.
console.log($.isNumeric('a')); // false
console.log($.isNumeric('1')); // true
console.log($.isNumeric(1)); // true
console.log($.isNumeric(1.5)); // true
console.log($.isNumeric('1.5')); // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Please try this:
if(Math.floor(manageridEntered) == manageridEntered && $.isNumeric(manageridEntered)){
//code here
}
Using Regex you can achieve it see below code
$(document).ready(function () {
$("#button").on("click", function () {
var patt = new RegExp("^[0-9]*$");
if (patt.test($("#number").val())) {
alert("true")
} else {
alert("false")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="number" />
<input type="button" id="button" value="Check"/>
returns true if it's an integer
if(manageridEntered == parseInt(manageridEntered))

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