0

Basically what I need to be able to register two types of code. The code type A has only numbers and the code Type B has numbers, one hyphen, one alphabetic value and one numeric value.

Hypothetical situation:

  • I register the code type A, the custom directive validate all values.
  • I need to register the code type B, I check the option 'Validate code Type B', the pattern is changed in order to make the validation, then all values entered are validated.

Code - Type A
12345678
32445678
56535678

Code with complement number - Type B
32445678-a1
32445678-a2
65434567-b1

The form

<form>
  <span>Insert code:</span><br/>
  <input type="text" data-ng-model="code" code-type>  <br/>
  <input type="checkbox" data-ng-model="validateCodeTypeB" /> Validate code Type B
</form>

Note: When the 'validateCodeTypeB' option is checked the regex will be changed too. But I don't know how to implement the second regex in order to validate the code Type B.

See the example

And the directive

app.directive('codeType', function () {
    return {
    require: 'ngModel',
    link: function (scope, element, attr, ngModelCtrl) {
        function codeTypeA(text) {
          if (text) {
            var transformedInput = text.replace(/[^0-9]/g, '');

            if (transformedInput !== text) {
                ngModelCtrl.$setViewValue(transformedInput);
                ngModelCtrl.$render();
            }
            return transformedInput;
          }
        return undefined;
        }            
        ngModelCtrl.$parsers.push(codeTypeA);
    }
    }  
});
1
  • you are having problem with regex too as well? or just issuing how to give it 2nd regex? Commented Jul 18, 2017 at 4:59

1 Answer 1

1

Here I have made you plnkr for your solution:

if(!scope.codeType){
    transformedInput = text.replace(/[^0-9]/g, ''); // For CodeTypeA
} else {
    transformedInput = text.replace(/[^a-z]/g,''); // For CodeTypeB, change it to your own regex
}

https://plnkr.co/edit/IfIeXhy7vZacLi2jKsMs?p=preview

but regex is different for CodetypeB , change it to your regex for codetypeB and its good to go.

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.