user2264941
user2264941

Reputation: 407

Dynamics Pattern Javascript

I got request on a remote service, this service give me fields with patterns as follows:

[a-zA-Zа-яА-ЯёЁ'+-]{1,100}
[0-9a-zA-Zа-яА-ЯёЁ'+-]{2,10}

In square bracket contains allowed symbols. In curly brackets contains minimal and maximum symbols.

So I have fields and their patterns.

How I can validate entered data by incoming pattern?

Upvotes: 0

Views: 78

Answers (3)

Floris
Floris

Reputation: 46365

A simple example:

var s = "hello123";

var r1 = "[a-zA-Zа-яА-ЯёЁ'+-]{1,100}"; // the pattern you were given
var reg1 = RegExp("^" + r1 + "$");     // the pattern enclosed in `^` `$`

var r2 = "[0-9a-zA-Zа-яА-ЯёЁ'+-]{2,10}";
var reg2 = RegExp("^" + r2 + "$");

alert(reg1.test(s)); // false
alert(reg2.test(s)); // true

The regular expression has the pattern you mentioned, but enclosed between ^ and $ - meaning "the whole expression". The first expression fails because there is a number in s which is not allowed. The second expression passes - it has only numbers and letters, and between 2 and 10 characters total.

Upvotes: 0

Aaron
Aaron

Reputation: 77

You should use JavaScript regular expression to solve this.

you can do like this

"some test".match(/[a-zA-Zа-яА-ЯёЁ'+-]{1,100}/)

which returns ["some"]

or

/[a-zA-Zа-яА-ЯёЁ'+-]{1,100}/.test("some test")

which returns true

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

Send the string to the RegExp constructor and use test.

For example:

string = "[a-zA-Zа-яА-ЯёЁ'+-]{1,100}"
pattern = new RegExp(string)

alert(pattern.test("This works, привет, 123"));
alert(pattern.test("$☛☛"));

Live demo

Depending on your situation, you might want to add "^" and "$" to the pattern.

Upvotes: 1

Related Questions