How do I get the tag size?

1

To make validation of date field, the fact is that I can not get 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 reporting a correct date, type "12/12/2012", the function returns false.

    
asked by anonymous 19.09.2018 / 01:11

1 answer

1

.value was missing before .length in second condition:

data.value.length != 10

But it has too many parentheses in the condition. It could look like this:

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

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

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

if(data.value.length != 10)
  

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

Another thing, return true does not need else . If you enter if returning false , it will exit the function, so 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;
}
    
19.09.2018 / 01:14