-2

Looking for help on a regex for JS and adding a few more characters. This is what it currently includes (I think):

  • All alphanumeric characters
  • space
  • apostrophe
  • period (dot)
  • comma
  • underscores and hyphens

My current regex here:

/^[\w-\.-\,\s-']+$/

Can it be formatted better? This is for a <input> text field on a web form, and I'm open to additional suggestions or potential downfalls on my current statement.

Finally, how would I additionally include $ and & and % characters?

The JS that checks against my regex is this:

function has_error(el, type) {

    var textReg = /^[\w-\.-\,\s-']+$/;

    if ( el.val() == '' || (type=='text' && !textReg.test(el.val())) ) {
        // apply error logic
        return true;
    } else {
        // clear error logic
        return false;
    }
}
Dario Zadro
  • 1,143
  • 2
  • 13
  • 23

1 Answers1

1

Careful, a dash within a character class denotes a range, which you don't want here. Place the dash at the start or end to avoid this. Also, no need to escape the punctuation marks:

/^[\w.,'\s-]+$/

Adding more characters is easy:

/^[\w.,'\s$%&-]+$/

Note that $ means a literal $ within a character class and not the "end-of-string-anchor".

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Actually, the `'` is not working on iOS. Any ideas to update the regex for iOS Safari? – Dario Zadro Feb 09 '21 at 18:31
  • What do you mean by "is not working"? Does it not match the apostrophe? Maybe your text contains typographic apostrophes like `‘’‛′`? Try copying and adding them to your regex. – Tim Pietzcker Feb 10 '21 at 09:53
  • My function is preventing form submission with iOS apostrophes. I'll try to add them in. – Dario Zadro Feb 10 '21 at 14:19