0

For a form validation I use a very simple comparism. If y >= x then it returns false.

I have solved my problem by using parseInt(), but I don't understand why I need this function for only ONE value. Eat code:

function validateForm() {
        var x = parseInt(document.forms["einstform"]["zeit1"].value);
        var y = parseInt(document.forms["einstform"]["zeit2"].value);
        if (y >= x) {
            alert("Nope." + " " + x + " " + y);
            return false;
        }
    }

And this is my form for that:

<form name="einstform" action="a file" method="GET" onSubmit="return validateForm();">

    <select name="zeit1">
      <option value="30">1 Month</option>
      <option value="60" selected>2 Months</option>
      <option value="90">3 Months</option>
    </select>

    <select name="zeit2">
      <option value="0">Never</option>
      <option value="7">1 Week</option>
      <option value="14" selected>2 Weeks</option>
      <option value="21">3 Weeks</option>
      <option value="30">4 Weeks</option>
      <option value="42">6 Weeks</option>
      <option value="60">8 Weeks</option>
      <option value="84">12 Weeks</option>
    </select>

I guess this is simple to understand. It just compares selected values and cancels the form submit when y >= x. And it works pretty well, yes. But if I select in the second select "1 Week" (value = 7), the script always tells me 7 >= 30.

Sure, it may get a string value for that 7, for that I have to use parseInt() (and with that it works).

But why does the int comparism of all other values work perfectly, except for that 7?

Is this just random to tell me "always use parseInt()" or is there more to understand why a 7 refuses to be an int value?

Trollwut
  • 541
  • 1
  • 7
  • 23
  • 1
    If you don't parse the value as integer, then it is interpreted as a string and "7" >= "3" – Alvaro Montoro Mar 06 '15 at 15:12
  • 3
    Because `.value` is a string. Without `parseInt` you perform a lexicographic comparison, not a mathematical one – blgt Mar 06 '15 at 15:12
  • 2
    Probably related: http://stackoverflow.com/questions/10863092/why-is-string-11-less-than-string-3 – vvye Mar 06 '15 at 15:12
  • @wye I read your answer and it totally fits to my question. Sorry that I didn't found that answer before (didn't thought of a lexicographic comparism, my bad). – Trollwut Mar 06 '15 at 15:19

1 Answers1

2

if you don't parse the value with parseInt(), it's a string.

Else you get a string >= string

Now it is 7 >= 3 instead