How to allow typing only "yes" or "no" with Regexp in an input?

Asked

Viewed 131 times

2

What is the regular expression to allow you to type yes or no only in a field.?

It is allowing repeating the characters and cannot.

$('body').on("keyup",".logical",function(){
$(this).unbind('keyup').bind('keyup',function(e){ //vou buscar o evento keyup - quando o usuário solta a tecla

            var thisVal = $(this).val(); // atribuo o valor do campo a variável local
            var tempVal = "";

            for(var i = 0; i<thisVal.length; i++){
                if(RegExp(/^[s,y,e,n,o]$/).test(thisVal.charAt(i))){ // aqui estou usando uma expressão regular para limitar a entrada de apenas numeros ou seja digitos entre 0 e 9
                    tempVal += thisVal.charAt(i); //caso atenda a condição de ser um digito numérico, atribuo a uma variável temporária

                    if(e.keyCode == 8){
                        tempVal = thisVal.substr(0,i); //o keyCode == 8 é para eu poder usar o backspace para apagar algum numero indesejado.
                    }                       
                }
            }           
            $(this).val(tempVal); // ao terminar, atribuo o valor validado ao valor do campo passado para testar
        });});
  • 1

    Perhaps the most suitable component was two radio buttons, no?

1 answer

5


The regular expression that checks whether a string is "yes" or "no" is /^(yes|no)$/. But I believe that conceptually you are using the wrong component for this task.

Solution:

$('.apenasYesNo').bind('keypress', function(e) {
  var jaDigitado = $(e.target).val(),
      letra = String.fromCharCode(e.which);

  if(!/^(y|ye|yes|n|no)$/.test(jaDigitado + letra)) {
    e.preventDefault();   
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="apenasYesNo" />
<input class="apenasYesNo" />
<input class="apenasYesNo" />

EDIT: You can improve this implementation by allowing the user to edit a character at the beginning of the text by updating the code to:

function permitirApenasHorario(e) {
    var jaDigitado = $(e.target).val(),
        letra = String.fromCharCode(e.which),
        posicaoDoCursor = getCaretPosition(e.target),
        textoPretendido = insert(jaDigitado, posicaoDoCursor, letra);

    if(!regExpDeHorario.test(textoPretendido)) {
        e.preventDefault();
    }
}

Where getCaretPosition (withdrawn from here) is:

function getCaretPosition(field) {
    var caretPosition = 0;

    if (document.selection) { 
        //Suporte ao IE
        field.focus();

        var range = document.selection.createRange();
        range.moveStart('character', -field.value.length);
        caretPosition = range.text.length;
    } else if (field.selectionStart || field.selectionStart == '0') {
        // Suporte ao Firefox 
        caretPosition = field.selectionStart;
    }

    return caretPosition;
}

And insert is:

function insert(string, index, value) {
    return [
        string.substring(0, index),
        value,
        string.substring(index, string.length)
    ].join('');
}

Example: This improvement is useful if you want to use this feature to force the user to enter a correct time value, and he may eventually want to edit the hours without erasing the minutes. Try it with regexp: var regExpDeHorario = /^([0-2]|([0-2]|[01]\d|2[0-3])|([0-2]|[01]\d|2[0-3]):|([0-2]|[01]\d|2[0-3]):([0-5])|([0-2]|[01]\d|2[0-3]):([0-5])\d)$/;

  • 1

    very good! +1

  • Very good, that’s just what I needed!. Thank you!

  • more a doubt already this as 'yes' would have a way to type by Ima ? without needing to delete to type the 'no'?

  • What do you mean, @Gustavo? Explain better

  • when copying your code, when you type in the "yes" field you need to delete the "yes" to enter the "no" it does not erase automatically , if I replace the e.preventDefault(); for $(e.target). val(""); works more or less.

  • @Gustavo maybe my edition will help you! At a glance, tell me if you understand...!

Show 1 more comment

Browser other questions tagged

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