Search code examples
javascriptangularjsvalidationfilterinput-field

AngularJS Filter, set class of of label and input field with validation


I have an Angular app with a list of F1 drivers. I want to put a filter on the table, so I can get drivers by their first or by their last name. To make this I use following design: text input validation

Normally the label and the line of the input are black. I want to check if the input value only is a String value (a-zA-Z). I use following code in my partial view:

<div class="form-group col-xs-5 col-md-3">
    <label class="control-label" for="inputError">input must be [a-zA-Z]</label>
    <div class="form-control-wrapper">
        <input ng-model="nameFilter" type="text" name="nameFilter" class="form-control empty" placeholder="Search Driver name...">
        <span class="material-input"></span>
    </div>
</div>

This input value is bound with following filter (declared in my controller.js)

$scope.searchFilter = function (driver) {
    var re = new RegExp($scope.nameFilter, 'i');
        if(! (/[^a-zA-Z]+/).test($scope.nameFilter)){
            $scope.nameFilter.class ='control-label';
        }
    return !$scope.nameFilter || re.test(driver.Driver.givenName) || re.test(driver.Driver.familyName);
};

But this doesn't work.. What am I missing?


Solution

  • Regex

    Your Regular expression is wrong, check out its validity here

    change it from

    /[^a-zA-Z]+/
    

    to

    /^[A-Za-z]+$/