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.
Solution 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 #
functionvalidateUSSD(str){
var regex = /^\*[0-9\*#]*[0-9]+[0-9\*#]*#$/;
var valid= regex.test(str);
console.log(str, valid)
return valid;
}
functionhandleClick(){
var val = document.getElementById("ussdNo").value;
validateUSSD(val)
}
functionsamlpeTests(){
validateUSSD("*12344#");
validateUSSD("*#");
validateUSSD("****#");
validateUSSD("12344#");
validateUSSD("*12344");
validateUSSD("****5###");
}
samlpeTests();
<inputtype="text"id="ussdNo" /><buttononclick="handleClick()">Validate USSD</button>
Solution 2:
You can use the following Regex:
^\*[0-9]+([0-9*#])*#$
The above regex checks for the following:
- String that begins with a *.
- Followed by at least one instance of digits and optionally * or #.
- 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!
Solution 3:
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));
Solution 4:
Check here it will work for you
- Starts with *
- Ends with #
- can contain *,#, digits
- Atleast one number
functionvalidate(elm){
val = elm.value;
if(/^\*[\*\#]*\d+[\*\#]*\#$/.test(val)){
void(0);
}
else{
alert("Enter Valid value");
}
}
<inputtype="text"onblur="validate(this);" />
Post a Comment for "Regular Expression For Ussd Code In Javascript"