1

My text box should only allow valid ussd code

Starts with *

Ends with #

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

Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143
Sadashiv
  • 387
  • 1
  • 6
  • 17

5 Answers5

1

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>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
1

This regex works perfect for USSD shortcodes:

Regex Pattern: /^*[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. The regex I've provided does not support chaining "*" or "#" e.g "**" or "##" shortcodes will be rejected.

Julian Tabona
  • 325
  • 3
  • 13
0

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!

anacron
  • 6,443
  • 2
  • 26
  • 31
  • Extra note: Whilst this matches the OPs description of a USSD, it fails for a broad variety of them (e.g. `##004**16#` is a valid USSD). – Luke Briggs Feb 23 '17 at 12:58
0

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));
vatz88
  • 2,422
  • 2
  • 14
  • 25
0

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);" />
Sagar V
  • 12,158
  • 7
  • 41
  • 68