How do I get the tag size?

Asked

Viewed 23 times

1

I’m validating the data field, the fact is that I’m not getting the size of the field, see:

<form action="" onsubmit="return valida()">
    <input type="text" name="data" id="data"/>
    <input type="submit" name="cadastrar"/>
</form>

............

function valida()
{
    var data = document.querySelector("#data");
    if((data.value == "")||(data.length != 10))
    {
        alert("Informe uma data válida");
        data.focus();
        return false;       
    }
    else
    {
        return true;
    }
}

Even stating a correct date, type "12/12/2012", the function returns false.

1 answer

1


Missed the .value before the .length in the second condition:

data.value.length != 10

But there are too many parentheses in the condition. It could be so:

if(!data.value || data.value.length != 10)

The !data.value already checks if the field is empty.

However the !data.value is still redundant, since the data.value.length != 10 will only validate if there are exactly 10 characters. It could just be like this:

if(data.value.length != 10)

Just one observation: for date validation purposes, check only the number of characters does not mean that it is a valid date.

Another thing, the return true doesn’t need else. If you enter the if returning false, will exit function, hence the else is unnecessary:

function valida()
{
    var data = document.querySelector("#data");
    if(data.value.length != 10)
    {
        alert("Informe uma data válida");
        data.focus();
        return false;       
    }
    return true;
}
  • Thanks, the true Return needs Else because it is part of another script, here I only took a piece, and as for the validation I know it is not enough yet.

  • Blz. They were general tips. But the question is the lack of .value before the .length.

  • Sorry, I didn’t know, I’ll mark them all.

Browser other questions tagged

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