Form validation with index()

Asked

Viewed 442 times

1

I know you can validate with HTML5 or CSS, but just out of curiosity: I found a code on the net that checks if 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 cannot understand how this conditional value "-1" can be legitimate if there is no negative array or string value.

However basing myself on a thread of logic I assumed that "-1" meant "not to exist", hence I modified this to <0 and then to <1 and the two also worked.

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

  • 1

    If the answer solved your problem you can mark as accepted.

1 answer

2


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

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

  • -1 if there is no array or string for the searched value
  • of 0 and forward is for case it exists and then the number is the position of the element in the String and Array

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

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

  • Perfect man. What do you think of this improvement I made? http://jsfiddle.net/fmts9q4h/. The premise is that if "@" is okay, there has to be a "." at least 2 houses after "@", not to be "@.". Now it is validating perfectly without loopholes. The "" condition is not required.

  • I tried to add this condition in the same if "Indice.lastIndexOf('.') == Indice.length". It is to test whether in the e-mail the last character is a "." ; but it is not working, the rest is, see http://jsfiddle.net/sfd6t9co/

  • forgot me?

  • @ropbla9 good morning. Sorry I have been full of work with the new website of Mootools. I will take a look in a little while and I comment on your idea.

  • ok. I wanted to talk Inbox with you but I can’t.

  • @ropbla9 I will be here a few minutes: http://chat.stackexchange.com/rooms/18484/tempore

  • I’m around here again...

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.