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))
Related
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;
}
});
});
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
I have created a validate function using JavaScript. I need a validation that tests that password field in a form to make sure it is:
At least 8 characters.
Contains a numeric value.
Contains an alphabetic value.
I just need an If statement inside my validate function
function Validate()
{
with(document.memberInfo) {
evt = new userInfo(username.value, password.value, email.value, firstname.value, lastname.value, age.value, description.value);
}
with(evt)
{
if((email.indexOf("#",0)==-1))
{
alert("The email must contain the # symbol.");
return false;
}
evt.printEvent();
}
return true;
}
using regx function you can validate ur form . here is the code .
var xstr="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$";
var str=Document.getElementById("id").value;
var ck=xstr.exec(str);
if(!ck || ck[0]!=str){
//code
}
you can use regex "/^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/" refer this link stackoverflow
JsFiddle
var regex = /^(?=.*[0-9])(?=.*[a-zA-Z]).{8,}$/;
function getValue() {
return document.getElementById("myinput").value;
}
function test() {
alert(regex.test(getValue()));
}
function match() {
alert(getValue().match(regex));
}
<input type="text" id="myinput" value="vexillology"/>
<button id="testBtn" onclick=test()>test</button>
<button id="matchBtn" onclick=match()>match</button>
Using regex is the way to go, but the more readable solution is probably:
function isValid(pass) {
return pass.length >= 8 && // at least 8 characters
/\d/.test(pass) && // contains a digit
/[A-Za-z]/.test(pass); // contains a letter
}
function isValid(pass) {
return pass.length >= 8 &&
/\d/.test(pass) &&
/[A-Za-z]/.test(pass);
}
var field = document.getElementById("password");
var output = document.getElementById("output");
field.onkeyup = function() {
output.innerHTML = isValid(field.value) ? "Valid" : "Not Valid";
}
<input type="text" id="password" placeholder="Enter password" />
<span id="output"></span>
Alternatively, you can put it all in one regex:
function isValid(pass) {
return /^(?=.*[A-Za-z])(?=.*\d).{8,}$/.test(pass);
}
JSFiddle
I want to write in text box and check if is integer and less than 16 numbers. I have the following JavaScript codes.
<script type="text/javascript">
function doCheck(field) {
if (isNaN(document.getElementById(field).value)) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else {
return true;
}
}
</script>
<form method="post" action="" onsubmit="return doCheck('number');">
national id=<input type="text" name="nat" id="number">
<input type="submit" name="submit">
</form>
document.getElementById(field).value.length
you can find the length of string inside the text box using this
function doCheck(field) {
var len = document.getElementById("number").val().length;
if(parse.Int(document.getElementById(field).value) && len < 16) {
return true;
}
else {
alert('your alert');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
}
be sure you parse it as an integer.
function doCheck(field) {
var input_value = document.getElementById(field).value;
if(isNaN(input_value) || parseInt(input_value,10) != input_value || input_value.length < 16) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else{
return true;
}
}
isNAN() checks whether a number is an illegal number of any type, not only integer. So you have to use something else there, a regular expressions maybe.
To get the length of the field you can simply use:
document.getElementById(field).value.length
I created a basic program where user input is turned into an alert on submission. I can't figure out why the program only works as intended if I use false rather than true as the first condition in my if/else statement. I'm sure this is very basic but I've failed to find anything of relevance. After a long search I decided to post the question. Any answers will be greatly appreciated.
The HTML:
<form id="greetingForm">
<input type="text" name="userInput" id="userInput"/>
<input type="submit" value="click" id="submit"/>
</form>
The broken script:
function output(){
var input = document.getElementById('userInput').value;
if(input == true){
alert(input);
}else{
alert('Say something!');
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The working script:
function output(){
var input = document.getElementById('userInput').value;
if(input == false){
alert('Say something!');
}else{
alert(input);
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The variable input will never be equal to the boolean true because it is a string. Try changing it to:
function output(){
var input = document.getElementById('userInput').value;
if(input != ""){
alert(input);
}else{
alert('Say something!');
}
}
To clarify ferd tomale's answer, it's one of the "weird" type conversion cases where a check on equality to true does not behave in the same way as check on equality to false.
"" == false -> true
"a" == false -> false, but
"" == true -> false
"a" == true -> false
You can switch to using typesafe comparison operators (===, !==), which behave much more predictable, but then you'll have to convert values to the correct type yourself. Or you can learn the quirks of JS's automatic type conversion when you use == or !=.
Because your input is a string. And string == true will be false.
You can set breakpoints to check them.