用于验证NEAR协议的帐户名称的正则表达式



我想对NEAR协议帐户地址进行准确的表单字段验证。

我在https://docs.near.org/docs/concepts/account#account-id-rules看到最小长度为2,最大长度为64,字符串必须是64个字符十六进制表示的公钥(在隐式帐户的情况下)或必须由"帐户ID部分"以.分隔,以.near结尾,其中&;Account ID &;由小写字母数字组成,由_-分隔。

下面是一些例子。

这里的最后4个案例应该被标记为无效(可能还有更多我不知道的案例):

  • example.near
  • sub.ex.near
  • something.near
  • 98793cd91a3f870fb126f66285808c7e094afcfc4eda8a970f6648cdf0dbd6de
  • wrong.near.suffix(invalid)
  • shouldnotendwithperiod.near.(无效)
  • space should fail.near(无效)
  • touchingDotsShouldfail..near(无效)

我想知道是否有一个经过良好测试的正则表达式,我应该在我的验证中使用。

谢谢。

注:最初我的问题指向我在https://regex101.com/r/jZHtDA/1上开始的东西,但从头开始这样感觉不明智,因为肯定已经有我可以复制的官方验证规则。

我已经查看了一些我希望使用某种验证的代码,比如这些链接,但我还没有找到它:

  • https://github.com/near/near-wallet/blob/40512df4d14366e1b8e05152fbf5a898812ebd2b/packages/frontend/src/utils/account.js 18
  • https://github.com/near/near-wallet/blob/40512df4d14366e1b8e05152fbf5a898812ebd2b/packages/frontend/src/components/accounts/AccountFormAccountId.js L95
  • https://github.com/near/near-cli/blob/cdc571b1625a26bcc39b3d8db68a2f82b91f06ea/commands/create-account.js L75

JS SDK的预发布(v0.6.0-0)版本带有内置的accountId验证函数:

const ACCOUNT_ID_REGEX =
/^(([a-zd]+[-_])*[a-zd]+.)*([a-zd]+[-_])*[a-zd]+$/;
/**
* Validates the Account ID according to the NEAR protocol
* [Account ID rules](https://nomicon.io/DataStructures/Account#account-id-rules).
*
* @param accountId - The Account ID string you want to validate.
*/
export function validateAccountId(accountId: string): boolean {
return (
accountId.length >= 2 &&
accountId.length <= 64 &&
ACCOUNT_ID_REGEX.test(accountId)
);
}

https://github.com/near/near-sdk-js/blob/dc6f07bd30064da96efb7f90a6ecd8c4d9cc9b06/lib/utils.js L113

你也可以在你的程序中实现它。

应该这样做:/^(w|(?<!.).)+(?<!.).(testnet|near)$/gm

分解

^                 # start of line
(
w              # match alphanumeric characters
|               # OR
(?<!.).       # dots can't be preceded by dots
)+
(?<!.)           # "." should not precede:
.                # "."
(testnet|near)    # match "testnet" or "near"
$                 # end of line

试试正则表达式:https://regex101.com/r/vctRlo/1

如果只匹配单词字符,用点分隔:

^w+(?:.w+)*.(?:testnet|near)$

  • ^字符串
  • 起始
  • w+匹配1+单词字符
  • (?:.w+)*可选重复.和1+字字符
  • .匹配.
  • (?:testnet|near)匹配testnetnear
  • $字符串结束

Regex演示

更宽一点的变体,匹配不包含点的空白字符:

^[^s.]+(?:.[^s.]+)*.(?:testnet|near)$

Regex演示

最新更新