My text box should only allow valid ussd
code
Starts with *
Ends with #
And in the middle only *
, #
and 0-9
should be allow.
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\*#]*#$/
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>
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.
You can use the following Regex:
^\*[0-9]+([0-9*#])*#$
The above regex checks for the following:
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
function validate(elm){
val = elm.value;
if(/^\*[\*\#]*\d+[\*\#]*\#$/.test(val)){
void(0);
}
else{
alert("Enter Valid value");
}
}
<input type="text" onblur="validate(this);" />