S
S
ScarletFlash2018-09-10 17:32:05
JavaScript
ScarletFlash, 2018-09-10 17:32:05

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?

What does it look like in real life
5b967f62bfe83122120782.gif
В консоль пишу из функции:
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
            }
        };
    }

toString из Lodash – ни на что не влияет. Без него то же самое.
namePatternExp такой: [a-zA-Z ]* (от отчаяния взял из оф. документации Angular)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dollar, 2018-09-10
@dollar

I propose such a simple experiment in the console:
5b968baf9dc20559535666.png

A
Anton Shvets, 2018-09-10
@Xuxicheta

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 question

Ask a Question

731 491 924 answers to any question