JavaScript - validate numeric only and within range - javascript

I have an asp form which has a number of fields. On submit I want to check, using javascript that a tickbox has been selected and that an 'amount' field in within a given range AND has numbers only. I'm struggling to get it to check all three in one go - at the mometn i have the following:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if (x<5 || x >250)
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
At the moment this is two seperate checks for tick box select and range.
Any ideas appreciated.

Create a function that can do this:
function validate(str, chk, min, max) {
n = parseFloat(str);
return (chk && !isNaN(n) && n >= min && n <= max);
}
then call it like so:
function validateForm()
{
if(!validate(document.forms["myForm"]["Amount"].value,
document.forms["myForm"]["agreesubmit"].checked, 5, 250)) {
alert("Please complete all required fields - Amount you wish to save");
return false;
}
}

Try using the isNan(). Tutorial found at http://www.w3schools.com/jsref/jsref_isnan.asp
Something like:
if (isNaN(x) || x < 5 || x > 250))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
Quick note you might be confused about the or/ands, so notice that the x<5 || x >250 is wrapped in () so that it can be partnered with the and numeric condition. Then, finally the whole if wraps the statements.

This will ensure it has numbers only first, then check the number against a range.
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["Amount"].value;
if( String(x).search(/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/) != -1
&&( x<5 || x >250 ))
{
alert("Please complete all required fields - Amount you wish to save");
return false;
}
else if ( myForm.agreesubmit.checked == false )
{
alert ( "You Must Agree To The Terms and Conditions" );
return false;
}
}
</script>
via http://ntt.cc/2008/05/10/over-10-useful-javascript-regular-expression-functions-to-improve-your-web-applications-efficiency.html

Related

Javascript Eval() thinks first value is a function

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)

Javascript form validation. Street Number. How to set accepted numbers to 1 but accept numbers 1-99999

I'm having trouble with some JS form validation.
I've linked a external .JS script in my html head section with function rules.
I have the following function rule in the .JS script file:
function IsValid5DigitStreetNumber( str ) {
// Return immediately if an invalid value was passed in
if (str+"" == "undefined" || str+"" == "null" || str+"" == "")
return false;
var isValid = true;
str += "";
// Rules: zipstr must be 5 characters long, and can only contain numbers from
// 0 through 9
if (IsBlank(str) || (str.length != 1) || !IsInt(str, false))
isValid = false;
return isValid;
}
I have the following JS code in my html head section
if(IsValid5DigitStreetNumber(document.orderbooks.querySelectorAll("[name=streetnumber]")[0].value)) {
} else {
alert("Street Name invalid! Please enter a valid 1-99999 digit street number!:");
return false;
}
It's throwing up the alert message every time even when I enter a correct number.
I want to be able to accept a number between 1 and 99999 in the html form for street number. What do I change to get it working?
Edited:
After determining requirements at last:
function IsValid5DigitStreetNumber( str ) {
if (!/^\d{1,5}$/.test(str)) {
return false;
}
const num = parseInt(str, 10);
return num >= 1 && num < 1e5;
}

How to make an input to accept only two decimals and have maximum of 10 digits?

How to make an input to accept only two decimals and have maximum of 10 digits?
I use a function that is activated at onkeypress and gets the length of the value inserted in my input. I got to make it to accept max 10 digits, and maximum of 2 decimals, but after I put those 2 decimals, I can't introduce any other number. For example if I have 1234.11, I can't make it to 10234.11.
function onlyNumbers(){
if($('#GoalQuestionValue').val().toString().length>10) return false;
if($('#GoalQuestionValue').val().indexOf('.') != -1 && $('#GoalQuestionValue').val().toString().length-$('#GoalQuestionValue').val().indexOf('.') >2) return false;
}
function onlyNumbers(){
var n = $('#GoalQuestionValue').val().toString().split('.');
if(n[0].length > 8 || n[0].length < 2) return false; else return true;
}
Why not use a regex to validate this requirement:
if($('#GoalQuestionValue').val().toString().match(/[0-9]{8}\.[0-9]{2}/)!=null && $('#GoalQuestionValue').val().toString().length>11)
try keyup and keydown functions instead of onclick or onchange.
I think you have to check in keypress listener for digit input -
$("#GoalQuestionValue").keypress(function (e) {
if (e.keyCode >= 48 && e.keyCode <= 57) {
if (!isValidNumberStr(this.value)) return false;
}
})
Instead of "onclick" try to use events "onchange" or "oninput".
If you are talking about algorithm, I think this is the best one:
function onlyNumbers() {
var myArray = $('#GoalQuestionValue').val().toString().match(/([0-9]*)\.?([0-9]*)?/);
if(myArray[1]) {
if(myArray[1].length > 10)
return false;
if(myArray[2]) {
if( myArray[2].length > 2 )
return false;
if( myArray[1].length + myArray[2].length > 10)
return false;
}
return true;
}
return false;
}

javascript form validation textfield length

i got a problem on validate the student ID, it require 10 numbers, the problem i met is when i key in a valid student ID, it still return false. Please help me to check mycoding, thank you very much.
example of my Student ID = "1101106363"
if ((document.appsub.id.value == "") || !(isNaN(document.appsub.id.value)) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
update: [link]http://jsfiddle.net/rVswq/1/
You need to use document.getElementById method to select the element properly.
var el = document.getElementById("yourid");
if (!(isNaN(el.value)) || (el.value.length &lt 11))
{
alert("Please enter the correct Student ID");
el.focus();
return false;
}
There is something strange here.
You are checking if the value is null, OR if it IS a number (isNaN returns true if the value IS NOT a number, if you place !isNaN the result is true if the value IS a number), OR if the length is inferior to 11.
If you want to be sure that the inserted value is not null, a number and its length inferior to 11 you should write
if ((document.appsub.id.value == "") || isNaN(parseInt(document.appsub.id.value)) || (document.appsub.id.value.length > 10))
It looks to me like you don't need the NOT operator
if ((document.appsub.id.value == "") || isNaN(document.appsub.id.value) || (document.appsub.id.value.length < 11))
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
Your IF statement is wrong. You want:
if ( (document.appsub.id.value == "") || (isNaN(document.appsub.id.value)) || document.appsub.id.value.length < 11) )
{
alert("Please enter the correct Student ID");
document.appsub.id.focus();
return false;
}
Your if statement will catch students ids with length less to or equal to 10.
Test against length like 10 instead

Really basic javascript, checking a condition using || (or)

I am very new to JavaScript, and trying to learn using lynda.com.
I'm currently playing around with the if statement.
The code in question:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
if ( value == 2 ) {
alert("You have chosen 2.");
}
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
This is what i want to happen: If the number is NOT 1 or 2, i want JS to execute this piece of code:
if ( value != (1 || 2) ) {
alert("Invalid number. Try again.");
}
Apparently this is not the correct way to write it out, and i've tried writing it a bunch of different ways. Can someone show me the correct way, possibly using the else statement?
if ( value != 1 && value != 2) {
alert("Invalid number. Try again.");
}
If you write value != (1||2), the (1||2) will get first evaluated to 1 and then compared to value, so you effectively wrote:
if ( value != 1 ) { [...] }.
This is because the () have a higher predence than !=. You can also read this explanation about operator predence which gives more details.
1
if ( value != 1 && value !=2 ) {
alert("Invalid number. Try again.");
}
2
if ( !(value == 1 || value ==2) ) {
alert("Invalid number. Try again.");
}
3
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
The best way to write this statement would be as follow:
if ( value == 1 )
{
alert("1");
}
else if ( value == 2 )
{
alert("2");
}
else
{
alert("no 1 or 2");
}
The if statement that you are messing on is (1 || 2)
What will happen is it will do a Boolean test and return 1.
it should look like this
if ( value !== 1 && value !== 2 )
{
alert("no 1 or 2");
}
Thanks
As already noted, the best is to separate into two NOT statements,and evaluate both:
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
However, you could also use the if, else if, else pattern to cover yourself against all other inputs (letters, punctuation, whitespace, etc). The else acts as a catch-all at the end:
var value = prompt("1 or 2?");
if ( value == 1 ) {
alert("You have chosen 1.");
}
else if ( value == 2 ) {
alert("You have chosen 2.");
}
else {
alert("Invalid number. Try again.");
}
Inline statements like: (1 || 2) only evaluate the right hand side of the || if the left hand side is false-y. So what your statement actually is saying is:
if ( value != 1 )
Because 1 evaluates to true.
As most others have pointed out, what you actually want to do is:
if ( value != 1 && value != 2 )
The logic is incorrect. You have to do in this way
if ( value != 1 && value != 2) ) {
alert("Invalid number. Try again.");
}
the (1||2) statement is evaluated as 1 so you are testing if value != 1
have tried writing
if(value != 1 && value != 2)
You have to do it like
if ( value != 1 && value != 2 ) {
alert("Invalid number. Try again.");
}
OR
if (!(value == 1 || value == 2)) {
alert("Invalid number. Try again.");
}
You can use switch as follows
switch(value) {
case 1:
alert("You have chosen 1.");
break;
case 2:
alert("You have chosen 2.");
break;
default:
alert("Invalid number. Try again.");
}
Your problem is here:
if ( value != (1 || 2) )
What ths is doing is checking if "value" is not equal to (1 OR 2), where (1 OR 2) is evaluated first, because it's in the brackets. (1 OR 2) evaluates to 1, since 1 is truthy in javascript. What your code is actually doing is checking if your value is not equal to 1.
What you actually want to do is check if your value is !=1 and that your value is !=2. You do that like this:
if (value !=1 && value !=2) { /* do something */ }
You don't need a clause. You can just use:
else{
}

Categories

Resources