Reputation: 37
Can anyone tell me what are the alternatives to validate user input? this is just a very basic code I wrote today.
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>");
}
Upvotes: 1
Views: 522
Reputation: 941
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
Upvotes: 1
Reputation: 1125
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();
}
Upvotes: 0