-2

I am trying to validate an input text field using the following code but when i type in any letter it throws the else yet i want it to allow any letter but does not begin with a digit

     <div class="input-group">
        <label for="c_name">Cashier Name
        <input id="c_name" type="text" name="cashier_name"> 
        </label>
    </div>

$(document).ready(function(){
    $( "#c_name" ).keyup(function() {

        var data= /^[A-Za-z]+$/;
    if ($("#c_name").val() == data) {
        $(this).addClass("cash");
        $(this).removeClass("cashs");
    }else{
     $(this).addClass("cashs");
     $(this).removeClass("cash");
    }

});

}); ```

I expect it to add a class cash if it begins with a letter.
j08691
  • 204,283
  • 31
  • 260
  • 272

1 Answers1

1

data is RexExp.To check whether string matches the regex you should use RegExp.prototype.test

if (data.test($("#c_name").val()))

$(document).ready(function(){
    $( "#c_name" ).keyup(function() {
        var regex = /^[A-Za-z]+$/;
        if (regex.test($("#c_name").val())) {
            $(this).addClass("cash");
            $(this).removeClass("cashs");
        } else {
            $(this).addClass("cashs");
            $(this).removeClass("cash");
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group">
        <label for="c_name">Cashier Name
        <input id="c_name" type="text" name="cashier_name"> 
        </label>
    </div>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73