1

Can anyone tell me what are the alternatives to validate user input? this is just a very basic code I wrote today.

  • there is a button coded in HTML
  • when the user click on it, it will prompt for input
  • the input is only numbers


var a, b;
function cal(){
    a = prompt("enter the width");
        while(isNaN(a) || a <= 0 || a > 1000){
        alert("Invalid Input, enter it again!");
        return cal();
            }
    b = prompt("enter the length");
        while(isNaN(b) || b <= 0 || b > 1000){
        alert("Invalid Input, enter it again!");
        return cal();
            }
    result(a,b);
    }
function result(a,b){
    var perimeter = (2*a)+(2*b);
    var area = (a*b);
    document.write("Perimeter: "+perimeter+"<br>");
    document.write("Area: "+area+"<br>");
    }
MPelletier
  • 16,256
  • 15
  • 86
  • 137
vincentChen
  • 37
  • 1
  • 5

2 Answers2

1

One alternative is to use the new HTML5 input types and fall back to something like this if the browser does not support the new input type yet.

<input type="number" min="1" max="1000" />

But don't forget you still must do server side validation!

There are many great resources online and on SO on how to do this.

HTML Text Input allow only Numeric input

Community
  • 1
  • 1
Haohmaru
  • 901
  • 13
  • 19
  • 1
    Good suggestion. One nitpick...in order to replicate what the original code is doing, the OP would also have to use the mix, max attributes as well. – Mahesh Guruswamy Aug 19 '13 at 16:23
  • @Haohmaru, I just started javascript today, so only touching on the basic stuff, didn't know much about PHP or any server-related languages.But thanks anyway – vincentChen Aug 20 '13 at 02:19
  • @vincentChen cool buddy, may i suggest reading through the awesome [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript?menu) docs, and here's a +1 to get you going on SO. – Haohmaru Aug 20 '13 at 19:04
0

You can use a regex in your confirms:

var ptrn=/\D/g; // 'D' is any non-digit
if(ptrn.test(b) || b <= 0 || b > 1000){
    alert("Please enter only integers between 0 and 1000!");
    return cal();
}
williambq
  • 1,125
  • 7
  • 12
  • regex is only use to validate numeric input right? I already done that using "isNaN". Isn't it the same? – vincentChen Aug 20 '13 at 02:22
  • No, this is a non-digit pattern I have shown. `isNaN` would return false for any number (or true if you use `!isNaN`, including decimal or negatives or anything that can be coerced to a number. This means 1.5 would pass a `isNaN` test with 0-1000 bounds. – williambq Aug 26 '13 at 16:12