Form Validation with indexOf ()

1

I know that you can validate with HTML5 or CSS, but it's just out of curiosity: I found a code on the net that verifies that the syntax of a typed email is correct:

if(document.dados.email.value=="" || document.dados.email.value.indexOf('@') == -1 || document.dados.email.value.indexOf('.')  == -1 ) 
        { 

And it works. The problem is that I can not understand how this "-1" conditional value can be legitimate if there is no negative array or string value.

However based on a lint of logic I assumed that "-1" meant "does not exist", hence I modified this to <0 and then to <1 and both worked as well.

Could you please give me a clearer explanation of this case?

    
asked by anonymous 05.11.2014 / 07:59

1 answer

2

indexOf() exists for Arrays and Strings , works basically the same way:

(Note that the Arrays method is newer and only available in IE9 +)

  • -1 if the searched value does not exist in the array or string
  • from 0 and forward is in case there is and there the number is the position of the element in String and Array

In your case, when you have document.dados.email.value.indexOf('@') == -1 this check gives true if there is no at sign ( @ ) in the String.

In the case of document.dados.email.value.indexOf('@') give 0 the validation should fail because this would be an email type @gmail.com without "username", so your idea of checking with < 1 makes a lot of sense.

    
05.11.2014 / 08:47