A
A
Alexey Yarkov2016-02-15 15:46:51
JavaScript
Alexey Yarkov, 2016-02-15 15:46:51

How to write an exclusive regular expression?

There is a chat with a list of reserved logins (bots). How to create a regular expression that will skip logins for registration that do not match the logins from the list? We need a regular expression so as not to fence another method for validation, but use the mongoose model.

login: {
    type: String,
    required: true,
    unique: true,
    validate: /[a-zA-Z\d_]{5,16}/          // <- вот тут нужно воткнуть регулярку
  }

UPD1: changed like this:
login: {
    type: String,
    required: true,
    unique: true,
    validate: {
      validator: function(v) {
        return /[a-zA-Z\d_]{5,16}/.test(v);
      },
      message: "Некорректный логин '{VALUE}'! Логин может содержать английские буквы, цифры и символ '_'. Допустимая длина логина от 5 до 16 символов."
      }
  }

But there is still no check for reserved logins. You can do an if in the validator, but then how do you change the message?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Cat Scientist, 2016-02-15
@yarkov

UPD: I'm sorry, the first edition of the answer is incorrect - I was too lazy to figure it out. Here is the code for your solution:

// Если просто регулярка, то:

var botLoginReg = /^(?!(login1|login2|login3)$)[a-z\d_]{5,16}$/i;

// Если есть массив с логинами (наверняка есть):

var botsLoginsArray = [
    'login1',
    'login2',
    'login3'
];

var botLoginReg = new RegExp(`^(?!(${botsLoginsArray.join('|')})$)[a-zA-Z\d_]{5,16}`, 'i');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question