A
A
Alexander2018-02-22 22:51:48
JavaScript
Alexander, 2018-02-22 22:51:48

How to check input[type=text] for allowed characters?

I want to <input id="js_validate" type="text" required />be able to specify only allowed characters
. And if any other character is entered, for example /, alert "Misprint, / is a prohibited character" is displayed.

$('#js_validate').on('input', validate);
function validate(e) {
  var $item = $(this),
    value = $item.val();
  var st = new RegExp('^[abcdefghjklmnprstuvwxyzABCDEFGHJKLMNPRSTUVWXYZ1234567890]$');
  if (st.test(value)) {
    // прошли проверку - всё ок
    return true;
  } else {
    // не даю ввести неправильный символ
    e.preventDefault();
    // подключен скрипт sweetalert.js
    // показываю алерт, что это была опечатка
    swal ( 'Опечатка' ,  'можно только буквы и цифры' ,  'error' );
  }
}

Help fix the code, please https://codepen.io/anon/pen/ZrRdPZ

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton fon Faust, 2018-02-22
@noobwpjs

varst = new RegExp('[^a-zA-Z0-9]+');
and change the condition to if (!st.test(value))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question