-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.
0

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.