E
E
Emptyform2018-02-02 10:25:35
JavaScript
Emptyform, 2018-02-02 10:25:35

How to correctly check a string for validity using regular expressions?

I'm trying to validate a string using regular expressions.
Examples found on the Internet are based on match()or test()
But this alone is not enough - if you just do str.match(/[0-9]/)it, the result will be non-empty if strthere is at least one number in it. And in this example, it is necessary that all characters in strbe numbers
. In general, for now, I do this:

var str = '123';
var strIsValid = !!str.match(/[0-9]/) && str.match(/[0-9]/).input === str;

Can you tell me if everything is like this in the example or should I do something differently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Tsvetkov, 2018-02-02
@Emptyform

/^[0-9]+$/

A
Alexander Taratin, 2018-02-02
@Taraflex

/^[0-9]$/.test(str)
or option for numbers not exceeding 9007199254740991
parseInt(str, 10).toString() === str

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question