Answer the question
In order to leave comments, you need to log in
Why is the same value in input either valid or not?
Hello.
I came across a strange thing when working with Angular forms.
Validation behaves in an unpredictable way, but we managed to identify several patterns:
- Numbers are always valid
- Letters are valid when added
- Letters are not valid when deleted
Tell me why it works this way and how to avoid such inconstancy?
validate(control: FormControl) {
const pattern: RegExp = namePatternExp;
console.log(control.value, pattern.test(toString(control.value)));
return pattern.test(toString(control.value)) ? null : {
validate: {
valid: false
}
};
}
Answer the question
In order to leave comments, you need to log in
links for reflection
jsfiddle.net/xuxicheta/41rvdwh0/7
https://angular-reactive-form-guuytj.stackblitz.io
https://learn.javascript.ru/regexp-methods#regexp-...
It is not written there, but regexp.test(str) with the g flag works the same as exec.
Those. if there is a g, then the regexp stops at the last successful match and remembers the index. On the next call, it starts from there.
When you add 1 letter, the next check is fed a segment starting from lastIndex, i.e. this is our last added letter. And it returns true. When you remove one letter, lastIndex is outside of the string and the search fails to return false.
In the case of a number, the regexp finds nothing and lastIndex remains 0, and since your condition is any number of letters, and zero letters is fine, it returns true
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question