0

I have a javascript to allow just letters, numbers, space, _, - in one input:

var re = /^([a-zA-Z0-9 _-]+)$/;
if (!re.test(form.titulo.value)) {
    alert("Error: Input contains invalid characters!");
    form.titulo.focus();
    return false;
}

the problem is, I want to allow ' too. So I can type something like: Ana's house, don't... I try to just add ' in the regex, but it didn't work:

/^([a-zA-Z0-9 _-']+)$/
0

2 Answers 2

5

This is because the hyphen in a character class indicates a range, unless it is at the end (where it clearly can't be a range) or is escaped. You can also remove capturing group as it is not required in your case.

  1. Escape -

    /^[a-zA-Z0-9 _\-']+$/
    
  2. Move - at the beginning or end of the class

    /^[a-zA-Z0-9 _'-]+$/
    

Demo

input {
  color: green;
}
input:invalid {
  color: red;
}
<input type="text" pattern="[a-zA-Z0-9 _\-']+" />

Sign up to request clarification or add additional context in comments.

1 Comment

@RickJoe I've added Live Demo, you can try in it
5

Use

/^([a-zA-Z0-9 _'-]+)$/

When - is not the first or last character in the brackets, it means you're selecting a range of characters, like when you do a-z or 0-9. When you wrote _-' it meant all the characters between _ and '.

You can also escape the - to keep it from having special meaning.

/^([a-zA-Z0-9 _\-']+)$/

BTW, you can use \w as an abbreviation for a-zA-Z0-9_, so your regexp can be simplified to:

/^[\w \-']+$/

2 Comments

In the simplified regex, you missed space
Thx, didn't notice that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.