I'm very new to JavaScript and I want to do an input check.
Here is my script:
function checkInp()
{
var x=document.forms["myForm"]["num"].value; // Get the value
if (isNaN(x))
{
alert("Not a number!"); // Check if the input is a number
return false;
}
var valuex=document.forms["myForm"]["num"].value; // Get the value, i don't know if i have to re-write this variable, if no, please comment.
Number(valuex); // Make the input a number
if (valuex.value > 480) {
alert("Too high!"); // See if the number is greater than 480. If yes, say that, if not, return normally.
return false;
}
else {
return;
}
}
I don't know what happens, but the script doesn't work since I added the second part (to check if the number is greater than 480).
Please help me, with full example if possible.
If i'm not wrong, i thnk you need just to do like this:
If(valuex > 480)..
The way I'll doing it:
Document selectorQuery is more understandable
Dont get the value multiple time
Use ParseInt to transform your var on number
Don't forget to return true if success
Code:
function checkInp() {
var x = document.querySelector('input[name="num"]').value;
if (isNaN(x)) {
alert("Must be a number");
return false
} else if (x > 480) {
alert("Must be under 480");
return false
}
return true
}
Related
I am writing a code. And here I have a problem how can I fix that. I have an input line, it takes a string or a number. So I need to check what is the output and get the answer. I need to give a simple solution. So I can't use functions or something like that.
let input = prompt('Enter your text.');
if (typeof input === "string") {
alert("You have string.");
} else if (typeof input === "number" && input > 30) {
alert("number more than 30");
} else if (typeof input === "number" && input < 30) {
alert("number less then 30");
}
prompt will always return a string.
If you want to check whether the string is composed purely of numerical values, you could use a regular expression:
if (/^[+-]?\d+(?:\.\d+)?$/.test(input)) {
// then it's purely numerical
const num = Number(input.trim());
// perform more operations on the number
} else {
// it's not composed of only numerical characters
}
If you don't want to use a regex, you can use Number alone, but then you'll also include values like Infinity which might not be desirable, and since Number('') gives 0, you'll have to check for that separately:
const num = Number(input);
if (input.trim().length && !Number.isNaN(num)) {
// then it's a number, use num
}
Another approach that I'd recommend is to avoid prompt entirely. Consider using a proper modal instead, such as a form with an input box and a submit button.
In such a case, if you want to require a numeric input, just do:
<input type="number">
I had a similar problem a few weeks ago and this is what I did:
function testNumber(test) {
if (isNaN(test) === false) {
console.log("this is a number");
} else {
console.log("this is not a number");
}
}
testNumber(4); // number
testNumber("4") // number
testNumber("string") // not a number
You can replace "test" for a variable if you don't want to use a function
if (isNaN(myVar) === false) {}
And you may want to add more checks if you want to differentiate between 4 and "4"
You can do
let input = prompt('Enter your text.');
if(isNaN(Number(input))){alert("You have string.")};
if (Number(input) > 30) {
alert("number more than 30");
} else if (Number(input) < 30) {
alert("number less then 30");
}
So it can change all Stringed-numbers to numbers and check if they are number with the isNaN function
I want if phone number starts with + it should accept 12 digits if it does not contain + it should accept 10 digit what changes I have to do?
My code is attached below.
function phvalid()
{
var a = document.getElementById('phone').value;
var gb = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (a=="") {
document.getElementById('ph').innerHTML="Enter Number";
}
if (a.match(gb))
{
document.getElementById("ph").innerHTML="";
// return true;
}
if(a.length!=10)
{
document.getElementById("ph").innerHTML="Enter 10 digits";
return false;
}
if(a.indexOf("+")==0)
{
document.getElementById("ph").innerHTML="Enter 12 digits";
return false;
}
else
{
document.getElementById('ph').innerHTML="";
}
}
Hope this will help you..!! I have used the simple startwith method.
function phoneValidator() {
var number = document.getElementById('phoneNumber').value
if(number.startsWith("+")) {
document.getElementById("phoneNumber").maxLength = 12;
}
else {
document.getElementById("phoneNumber").maxLength = 10;
}
}
<input type="text" name="phoneNumber" id="phoneNumber" onkeyup="phoneValidator()"/>
Firstly, your check for 10 digits overrides your check for 12. What I would do is:
function phvalid()
{
let phone = document.getElementById('phone');
let regex = /^([0|\+[0-9]{1,5})?([7-9][0-9]{9})$/;
if (phone.value=="") {
phone.innerHTML="Enter Number";
}
if (phone.value.match(regex))
{
phone.value.innerHTML="";
// return true;
}
if ( phone.value.charAt(0) != '+' && phone.value.length != 12 ){
if ( phone.value.length != 10 ){
phone.innerHTML = "Please enter a valid phone number, it should be 10 digits unless it is international in which case it should be 12 prefixed by a +";
return;
} else {
// Do whatever you need to do for a 10 digit phone number
}
} else {
// Do whatever you need to do for a 12 digit number
}
}
It is always easier to read your code later if you explain what you are doing, to yourself. The nested if, yes you could do it all on one line or use an iif there but when you come back to read it later, this will probably be easier to understand. I also set the result of the document.getElementById to a variable for both less typing and to make it clear what you are modifying. Your code you are modifying a different element. If that's what you are trying to do, it is still easier than calling getElementById every time you wish to modify it, calling and storing it means you only have to change it in one place if your code changes later instead of having a weird bug because you forgot to change it somewhere.
If I'm reading your regex right, the 10 digit phone number must start with a 0? It might be better to use:
let regex=/(^\+?\d{10,12}$)/;
I am writing a function that will evaluate expressions in an input field and return the sum.
Currently is working but I am running into an error that I just cannot figure out. Here is my code in Plunker.
function linkFunction(scope) {
var PO = 10;
scope.value = PO;
scope.result = '';
scope.Evaluate = function (input) {
if (input.match(/[a-zA-Z]/g) != null) { //to check if user has inputted a letter between a-z, case sensitive.
return alert("You must only use numbers, not letters")
} else if (input.match(/[!"^£$&[{}\]?\\##~<>_'|`¬:;,=]/g) != null) { //to check if user has inputted a special symbol
return alert("You must only use the symbols specified")
} else if (input.match(/\.\d*\.+/g) != null) { //to check if user has inputted a doubled decimal eg 10.2.2
return alert("You can only use 1 decimal point")
} else if (input.match(/\.{2,}/g) != null) {//to check if user has inputted a two decimals eg 10..1
return alert("You cannot put two decimals one after another")
}
// if (input.match(/\d*\(\d\W\d\)/g) != null){
// }
var percentPattern = /[0-9]*\.?[0-9]+%/g;
var expressionResults = input.match(percentPattern);
if (scope.enablePercentage) { //if parameter = 1, then do this code.
if (expressionResults != null) { //if user has entered into the input field
if (expressionResults.length > 1) { //if you user has finished the RegEx (%, is the end of the RegEx, so code will think its the end of the array, therefore you cannot add another %)
return alert("Too many % values");
} else {// user has met all requirements
var percentageValue = parseFloat(expressionResults) * PO / 100;
input = input.replace(expressionResults, percentageValue);
}
}
} else if (expressionResults != null) { //if parameter = 0, then do this code. Parameter is off, but user has entered percentage
return alert("You cannot use %");
}
scope.result = eval(input);
}
}});
If you write 10(5+3) it gives you an error
TypeError: 10 is not a function
Obviously if a user ran this code they would expect to see the value 80.
Eval thinks that 10() is a function.
Does anyone know how to fix this problem. Thanks
eval expects you to pass it JavaScript, not algebra.
If you want to multiply two values together then you must use a Multiplicative Operator.
10 * (5+3)
My question is about validating a form. I am doing a validation of two fields, one of them receives the value in decimal, example ($ 500.00), is already with mask.
In this field that receives the value, it can not be less than 300.00.
If it is smaller 300.00, a message will appear saying the value has to be greater than 300.00.
Summary: The validation checks that it is empty, but does not check if the (number) int is less than $ 300
I'm using it this way (there's more code, in short):
function valid_simulation(form1) {
if (form1.valor.value == ' ') {
alert("value is not valid");
return false;
}
if (form1.valor.value <= 300) {
alert("value is not valid");
return false;
}
}
Thanks for any help.
Your basic concept is correct: set the message when the if statement test is falsy. Something like the following:
function showFormError(message) {
$("#alertBox").text(message)
}
if (isInvalid) { showFormError("We have a problem.") }
If the dollar mark is the issue, You can split it and validate.
var userInput = $("#inputData").val();
if(userInput.includes("$")) {
var splitArray = userInput.split("$");
if (typeof splitArray[1] && parseFloat(splitArray[1]) < 300){
alert("Amount Not valid");
}
}
<button onclick="isleap(1992)">Try it</button>
function isleap(year);
{
var yr=document.getElementById("year").value;
if ((parseInt(yr)%4) == 0)
{
if (parseInt(yr)%100 == 0)
{
if (parseInt(yr)%400 != 0)
{
alert("Not Leap");
return "false";
}
if (parseInt(yr)%400 == 0)
{
alert("Leap");
return "true";
}
}
if (parseInt(yr)%100 != 0)
{
alert("Leap");
return "true";
}
}
if ((parseInt(yr)%4) != 0)
{
alert("Not Leap");
return "false";
}
}
http://jsfiddle.net/kcyCd/
Having problems figuring out how to get the code to popup the alert box with the answer to the leap year.
A simple isLeapYear function is:
function isLeapYear(year) {
var d = new Date(year, 1, 29);
return d.getMonth() == 1;
}
It just sees if 29 February occurs in the given year. You should be able to do:
function isLeapYear2(year) {
return !!Date.parse(year + '-02-29');
}
on the basis that parsing an invalid date should return NaN, which type-converts to false, but not all browsers correctly implement Date.parse. e.g.
isLeapYear2('2001'); // false in Firefox, true in IE
<button onclick="alert(isleap(1992));">Try it</button>
If you alert the value returned from the isleap function it should work. I'm not guaranteeing the answer that pops up will be correct though.
Your fiddle doesn't work because you've kept the default jsfiddle setting that places your JS in an onload handler, which means your function isn't global and isn't accessible from the inline onclick attribute - this should be changed in the drop-down on the left to one of the "no wrap" settings. Also, the first thing the function would do if called is try to read the value from an element with id "year" and you have no such element. You currently ignore the year parameter.
Having said that, your function is way more complicated than it needs to be. You can greatly simplify your code by doing the parseInt() once at the beginning, then do whatever it is you need to do if the value being tested isn't an integer, and then you can do the leap year test in just one line.
Also, if you're using parseInt() on user input you must specify a radix as the second parameter if you want to avoid obscure bugs due to input starting with a leading zero being treated as octal. So parseInt(year, 10).
Finally, why return strings "true" and "false"? Wouldn't it make more sense to return actual booleans so that you can call your function as:
if (isleap(1992)) {
// do something
}
Anyway, here's a short version:
function isleap(year) {
year = parseInt(year,10);
if (isNaN(year)) {
alert("Not a number");
return false;
}
if (year%4===0 && (year%100!=0 || year%400===0)) {
alert("Leap");
return true;
} else {
alert("Not leap");
return false;
}
}
Demo: http://jsfiddle.net/kcyCd/1/
If you didn't need to display the alert you could make it shorter still:
function isleap(year) {
year = parseInt(year,10);
if (isNaN(year)) {
alert("Not a number");
return false;
}
return (year%4===0 && (year%100!=0 || year%400===0));
}
And obviously it would be a one-liner if you didn't need to test for invalid values.
You're passing a value into the function, and then looking for a different value in the DOM that doesn't exist.
Also, the code is hard to follow since you merged true/false conditionals, and you're using a string instead of a boolean - which is bad, because if(isleap(1992)) will always be true in your code.
Simplified:
function isleap(year)
{
if(year % 4 == 0 || (year % 100 == 0 && year % 400 == 0)){
return true;
}
return false;
}