简体   繁体   English

JavaScript中ussd代码的正则表达式

[英]Regular expression for ussd code in JavaScript

My text box should only allow valid ussd code我的文本框应该只允许有效ussd代码

Starts with **开头

Ends with ##结尾

And in the middle only * , # and 0-9 should be allow.在中间只有*#0-9应该被允许。

This regex works perfect for USSD shortcodes:此正则表达式非常适合 USSD 短代码:

Regex Pattern: /^*[0-9]+(*[0-9]+)*#$/正则表达式模式: /^*[0-9]+(*[0-9]+)*#$/

Regex will ACCEPT the following正则表达式将接受以下内容

*1#
*12#
*123#
*123*1#
*123*12#
*123*12*1#

Regex will REJECT the following正则表达式将拒绝以下

*
#
*#
**123#
*123##
*123*#
*123*12*#

The answer marked as BEST ANSWER has limitations as it supports ****5### which was not desired in my use case.标记为最佳答案的答案有局限性,因为它支持****5### ,这在我的用例中是不需要的。 The regex I've provided does not support chaining " * " or " # " eg " ** " or " ## " shortcodes will be rejected.我提供的正则表达式不支持链接“ * ”或“ # ”,例如“ ** ”或“ ## ”短代码将被拒绝。

You can use the following Regex:您可以使用以下正则表达式:

^\*[0-9]+([0-9*#])*#$

The above regex checks for the following:上述正则表达式检查以下内容:

  1. String that begins with a *.以 * 开头的字符串。
  2. Followed by at least one instance of digits and optionally * or #.后跟至少一个数字实例和可选的 * 或 #。
  3. Ends with a #.以 # 结尾。

In Java script, you can use this to quickly test it out:在 Java 脚本中,您可以使用它来快速测试它:

javascript:alert(/^\*[0-9]+([0-9*#])*#$/.test('*06*#'));

Hope this helps!希望这可以帮助!

This should work /^\*[0-9\*#]*[0-9]+[0-9\*#]*#$/这应该工作/^\*[0-9\*#]*[0-9]+[0-9\*#]*#$/

 ussd = "*123#"; console.log((/^\*[0-9\*#]*[0-9]+[0-9\*#]*#$/).test(ussd)); ussd = "123#"; console.log((/^\*[0-9\*#]*[0-9]+[0-9\*#]*#$/).test(ussd));

Check here it will work for you在这里检查它会为你工作

  • Starts with *以。。开始 *
  • Ends with #以。。结束 #
  • can contain *,#, digits可以包含 *,#, 数字
  • Atleast one number至少一个号码

 function validate(elm){ val = elm.value; if(/^\*[\*\#]*\d+[\*\#]*\#$/.test(val)){ void(0); } else{ alert("Enter Valid value"); } }
 <input type="text" onblur="validate(this);" />

You can try following regex:您可以尝试以下正则表达式:

/^\*[0-9\*#]*[0-9]+[0-9\*#]*#$/

Rules规则

  • Starts with *以。。开始 *
  • Can have 0-9, *, #可以有 0-9, *, #
  • Must have at least 1 number必须至少有 1 个号码
  • Ends with #以。。结束 #

 function validateUSSD(str){ var regex = /^\*[0-9\*#]*[0-9]+[0-9\*#]*#$/; var valid= regex.test(str); console.log(str, valid) return valid; } function handleClick(){ var val = document.getElementById("ussdNo").value; validateUSSD(val) } function samlpeTests(){ validateUSSD("*12344#"); validateUSSD("*#"); validateUSSD("****#"); validateUSSD("12344#"); validateUSSD("*12344"); validateUSSD("****5###"); } samlpeTests();
 <input type="text" id="ussdNo" /> <button onclick="handleClick()">Validate USSD</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM