Patrick McDermott Patrick McDermott - 3 months ago 7
jQuery Question

if statement - field to accept only letters

Situation

I have a field which needs to only accept letters. An error pops up if there are numbers in

display_name
on submit, but if I enter pat123, it accepts it which I don't want.

Aim

To warn the user if anything but letters have been entered into
display_name
, so no numbers and symbols.

HTML

<input name="display_name" type="text"></input>


Javascript

var fieldNum = /^[0-9a]+$/;

var display_name = form.find('input[name="display_name"]').val();

if ((display_name.match(fieldNum))) {
console.log('error');
}

Answer

There are two things wrong in your code/logic.

First, the regex - why /^[0-9a]+$/? What´s with the a?

Secondly - if your regex matches, you log an error. That regex only matches a string of just digits (or a's).

What you want to do I believe is something like

var fieldNum = /^[a-z]+$/i;

var display_name = form.find('input[name="display_name"]').val();

if (!(display_name.match(fieldNum))) {
    console.log('error');
}

The regex is fixed and it checks if it doesn't match (!).