Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

javascript - Including a hyphen in a regex character bracket?

$.validator.addMethod('AZ09_', function (value) { 
    return /^[a-zA-Z0-9.-_]+$/.test(value); 
}, 'Only letters, numbers, and _-. are allowed');

When I use somehting like test-123 it still triggers as if the hyphen is invalid. I tried - and --

question from:https://stackoverflow.com/questions/65848656/how-to-make-restrict-input-in-javascript-can-only-input-arithmetic-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Escaping using - should be fine, but you can also try putting it at the beginning or the end of the character class. This should work for you:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...