Function to check combobox and select an appropriate Regexp

Asked

Viewed 80 times

-1

How can I insert a function that checks the optionlist and after that checks the regexp of the banks below? There are 8 digits allowed in regexp to check the account in each bank, I do not know how to do this function.

 function check(){
        var verificaInput = document.querySelector("#agencia").value;
        //Tá okay
        var reg = /^[0-9]{4}$/;
        
        if(reg.exec(verificaInput)){
          //Se for igual a true
          if(reg.test(verificaInput)){
            //Seu código aqui
            console.log("Passou");
          }
        }
        else{
          alert("Digite agência e conta novamente");
        }
        
    }
    
        
    function changebancos(){
        var selectedoption = document.getElementById("optionvalue");
        //A coleção de option do seu select
        var options = selectedoption.options;
        //options.length: pega a quantidade
       for(var i = 0; i < options.length;i++){
          console.log(options[i].value);
        }
    }
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test</title>
</head>
<body>
    <label>
    <select id="optionvalue" function="changebancos()" >

            <option value= "0">Banco do Brasil</option>
            <option value="1">Itaú</option>
            <option value="2">Bradesco</option>
            <option value="3">Santander</option>
            <option value="4">Sorocred</option>
        </select>
        <br>
        <input type="number" name="agencia" id="agencia"/>
        <br>
        <input type="number" name="conta" id="conta"/>
        <br>
        <input type="button" id="btnCheck"value="click to check" onclick="check(this.id)"/>
    </label>
       
</body>
</html>

The latter console.log which I placed is not returning anything on the console. I need it to return which option was selected after clicking the button btnCheck, and after that with a function check which bank was selected and check the Regexp checks.

  • It was not clear your question, could explain it better?

  • 1

    If you want to validate exactly 8 digits, use /^[0-9]{8}$/ - the number between keys indicates the amount. And if you want a maximum of 8 digits, use /^[0-9]{0,8}$/. And you don’t have to call exec and test, call only one of them (if you just want to know if it’s valid, use test, whether it wants to extract information from match, use exec) - read the documentation for the difference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

1 answer

0

The last console.log does not print anything because the function changebancos is not being called.

If you want her to be called every time select is changed, use onchange="changebancos()", and not function="changebancos()" (see the documentation).

Here is an example (I removed those parts of your HTML that were not essential to show how the onchange and the validation of select). In function changebancos i only printed the option chosen with console.log, but you can change to do whatever you need with this value:

function check() {
    // agência pode ter entre 1 e 4 dígitos
    let regAgencia = /^[0-9]{1,4}$/;
    // conta pode ter entre 4 e 8 dígitos
    let regConta = /^[0-9]{4,8}$/;

    let agencia = document.getElementById("agencia").value;
    let conta = document.getElementById("conta").value;
    if(regAgencia.test(agencia) && regConta.test(conta)){
        console.log("Passou");
    } else {
        alert("Digite agência e conta novamente");
    }
}

function changebancos() {
    let selectBanco = document.getElementById("banco");
    let opcao = selectBanco.options[selectBanco.selectedIndex];
    console.log(`Banco ${opcao.text} selecionado, valor=${opcao.value}`);
}
<form>
    <select id="banco" onchange="changebancos()">
        <option value= "0">Banco do Brasil</option>
        <option value="1">Itaú</option>
        <option value="2">Bradesco</option>
        <option value="3">Santander</option>
        <option value="4">Sorocred</option>
    </select>
    <input type="number" name="agencia" id="agencia"/>
    <input type="number" name="conta" id="conta"/>
    <input type="button" id="btnCheck"value="click to check" onclick="check()"/>
</form>

I also changed the regex. You were using /^[0-9]{4}$/, which checks exactly 4 digits. But then you mention 8 digits, and it was unclear whether it is exactly 8 or at most 8.

Anyway, for the agency I used /^[0-9]{1,4}$/ (the quantifier {1,4} means "at least 1 and at most 4", that is, the agency can have between 1 and 4 digits), and for the account I used /^[0-9]{4,8}$/ (not less than 4 and not more than 8 digits). Are just examples, adjust the values for what you need (if you want exactly 8 digits, for example, use /^[0-9]{8}$/).

I also used only the method test, because it is not necessary to call exec and test in sequence (so you are checking the same regex twice unnecessarily).

The method exec returns an array containing various information about the match found. If you will not use this information and just want to know if the string corresponds to regex, just use the method test, returning true or false.

Browser other questions tagged

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