当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - Regular expression for ussd code in JavaScript

问题描述:

My text box should only allow valid ussd code

Starts with *

Ends with #

And in the middle only * , # and 0-9 should be allow.

网友答案:

You can try following regex:

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

Rules

  • Starts with *
  • Can have 0-9, *, #
  • Must have at least 1 number
  • 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>
网友答案:

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:

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

Hope this helps!

网友答案:

This should work /^\*[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);" />
分享给朋友:
您可能感兴趣的文章:
随机阅读: