Answer the question
In order to leave comments, you need to log in
How to do validation in angular?
I need to make a page using Angular.
An empty white page in the middle of which the input should be.
Only characters {}[]() can be entered in input.
If any other character is entered under the input, the text "You entered invalid characters" should be displayed - the check should be immediately at the time of entering the values.
On the entered line, you need to validate open - closed brackets, namely, each open bracket must correspond to a closed one. Brackets can be nested within other brackets. For example:
{[()]({})} - valid
{()}()[{}] - valid
{{(})} - not valid
{) - not valid
[{}]) - not valid
Check result you need to write under the field, the check should be immediately at the time of entering the values.
I went the way of the stack and it works when characters are entered, and when they are removed from the input, the stack is filled. And one more thing, what to do when the user moves the cursor somewhere in the middle of the typed line and there will be something to enter?
Answer the question
In order to leave comments, you need to log in
Why is it so difficult? Make a validation function and call it every time the model changes.
we read the documentation for ngModelController , add our validator there in the form of an attribute directive for input.
.directive('brackets', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
var stack = [];
ctrl.$parsers.unshift(function(brackets) {
var pushed = function(el) {
var numLastElemStack = stack.length;
if (stack[numLastElemStack -1] === '{' && el === '}' || stack[numLastElemStack -1] === '[' && el === ']' ||
stack[numLastElemStack -1] === '(' && el === ')') {
stack.pop();
}
else {
stack.push(el);
return 'no valid';
}
};
if (/^[\[|\]|\(|\)|\{|\}]+$/.test(brackets)) {
var lastCharacter = brackets.substr(-1);
return pushed(lastCharacter);
} else {
return 'no valid';
}
});
}
};
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question