Prevent user from typing street type

Asked

Viewed 45 times

-1

My form has a drop for TYPE OF BACKYARD (Alameda, Avenue, Way, road, etc. the list is not large and could be included manually within the if) and an input to enter the NAME OF THE BACKYARD. I need to prevent the user from entering the STREET TYPE in the STREET NAME field, to avoid data duplicity. Thus, if the user enters "Rua das flores" in the NOME DO LOGRADOURO field, the form must immediately remove the string "Rua", either on onblur or in the form submission. What javascript function can I use to perform this task?

//drop com tipos de logradouro
        <div class="form-group col-xs-2">
            <label>Tipo de logradouro<span class="text-danger">*</span></label>
            <select id="tipoLogradouro" name="itemImovel.tp_logradouro" required class="form-control">
                <option value="" selected></option>
                @foreach (var item in ViewBag.TipoLogradouro)
                {
                    <option value="@item.propriedade_dominio1">@item.propriedade_dominio1</option>
                }
            </select>
        </div>
//input para nome do logradouro
        <div class="form-group col-xs-4">
            <label>Logradouro<span class="text-danger">*</span></label>
            <input type="text" id="logradouro" name="itemImovel.ds_logradouro" onchange="bucarCartorio(0);" maxlength="255" value="@Imovel.ds_logradouro" class="form-control" required>
        </div>

1 answer

0


There are several strategies for this, below one that should help.

//Pego todos os tipos que existem 
const tipos  = document.querySelectorAll("#tipoLogradouro option");
//Pego o input com a informação inserida
const iLogradouro = document.getElementById("logradouro");


//Criando uma função que faz a verificação
verificaLogradouros = function(){
    //armazeno o valor informado
    logradouro = iLogradouro.value;
    //Itero por cada tipo
    tipos.forEach((oTipo) =>{
    //armazeno o valor 
    tipoLogradouroAtual = oTipo.value;
    //crio uma ExpressãoRegular para verificar o que foi escrito de maneira 'Case Insensitive'
    re = new RegExp(tipoLogradouroAtual, "i");
    // verifico que no valor informado, aparece o texto
    if(re.test(logradouro)){
        //substituo o tipo por texto vazio
        iLogradouro.value = logradouro.replace(re, "");
    }
    });
};

//anexo ao evento blur 
iLogradouro.addEventListener('blur', verificaLogradouros);
  • It worked perfectly after a few adjustments. The function only does not remove the space that the user typed after the street, problem that I was able to solve using Trim()

  • I’m glad it worked... Remember to mark the answer.

Browser other questions tagged

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