grn_uk
grn_uk

Reputation: 35

JavaScript - validate numeric only and within range

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.

Upvotes: 2

Views: 37929

Answers (3)

Jared Drake
Jared Drake

Reputation: 1002

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.

Upvotes: 3

Mohamed Nuur
Mohamed Nuur

Reputation: 5655

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;
  }
}

Upvotes: 4

T.W.R. Cole
T.W.R. Cole

Reputation: 4166

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

Upvotes: 0

Related Questions