How to allow to enter only "yes" or "no" with RegExp in an input?

2

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

It is allowing you to repeat the characters and can not.

$('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
        });});
    
asked by anonymous 03.12.2014 / 20:57

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><inputclass="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 (removed from 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 deleting the minutes. Experiment 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)$/;

    
03.12.2014 / 21:17