[英]JavaScript Regex - How to check if a string only contains letters, numbers, dashes, underscores and dots
[英]How does a validation regex look like which allows letters, numbers, dashes and dots only, forces at least one dot but not as first character?
我真的不擅長正則表達式,但在我的 JavaScript 應用程序中,我正在嘗試驗證表單項,表單項的值只能包含字母、數字、破折號和至少一個點。
所以以下是有效的:
hello.world
microsoft.com
到目前為止,我想出了這個(.+)[a-zA-Z0-9.-]\.[a-zA-Z0-9.-]+$
但它不起作用,因為我可以添加空格。 我可以做些什么來使我的正則表達式工作? 我也可以防止點成為第一個字符嗎?
迄今為止接受的答案並不完全符合 OP 的要求,這些要求是......
表單項的值只能包含字母、數字、破折號和至少一個點。 ...另外...防止點成為第一個字符...
NJDawson的正則表達式... ^[^.][a-zA-Z0-9.-]+$
... 在最后一個要求中確實失敗了,因為它允許作為第一個字符的任何字符不是 OP 所在的點需要除點之外的任何上述引用字符。
例子:
const regX = (/^[^.][a-zA-Z0-9.-]+$/); console.log( "regX.test('.foo-bar.baz-9')?", // false as expected regX.test('.foo-bar.baz-9') // because of dot first. ); console.log( "regX.test('#foo-bar.baz-9')?", // true which violates regX.test('#foo-bar.baz-9') // the requirements ); // due to using #.
通過將正則表達式更新為更具表現力的內容,可以完全滿足要求... ^[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]*$
... 這使得確保除了允許的字符之一之外,點或任何其他字符都不位於要測試的字符串的第一個 position 處,並且除了其他允許的字符外,還強制字符串至少包含一個點。
更新示例:
const regX = (/^[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]*$/); console.log( "regX.test('.foo-bar.baz-9')?", // false as expected regX.test('.foo-bar.baz-9') // because of dot first. ); console.log( "regX.test('#foo-bar.baz-9')?", // false as expected regX.test('#foo-bar.baz-9') // because of hash first. ); console.log( "regX.test('+foo-bar.baz-9')?", // false as expected regX.test('+foo-bar.baz-9') // because of plus first. ); console.log( "regX.test('-foo-bar.baz-9')?", // true as expected. regX.test('-foo-bar.baz-9') ); console.log( "regX.test('9.-foo-bar.baz')?", // true as expected. regX.test('9.-foo-bar.baz') ); console.log( "regX.test('9a-foo-bar-baz')?", // false as expected. regX.test('9a-foo-bar-baz') // bacause of missing dot. );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.