0

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
  • 7,792
  • 23
  • 75
  • 128
Sadashiv
  • 317
  • 1
  • 5
  • 16

4 Answers4

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,093
  • 2
  • 24
  • 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,347
  • 2
  • 14
  • 23
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
  • 11,606
  • 7
  • 43
  • 64
0

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
  • 22,581
  • 5
  • 41
  • 70