Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How do I make + only appear once and at the front only like example +01234564789 in Regex Jquery. The character can't be everywhere and only front and appear only once in the textfield.

What I have tried:

I have try this, but its still have problem. So I really need help I'm a beginner for this so please help me.

$(function(){
$('#hpno').keypress(function(e){
var txt = String.fromCharCode(e.which);
console.log(txt + ' : ' + e.which);
if(!txt.match(/^\+*/ [0-9]+$/))
{
return false;
}
});
});
Posted
Updated 22-Aug-18 19:45pm

Try:
^\+?\d*$


If you want to work with regexes, then get a copy of Expresso[^] - it's free, and it examines and generates Regular expressions.
 
Share this answer
 
v2
Quote:
How do I make + only appear once and at the front only like example +01234564789 in Regex Jquery.

I think your problem is that you have not understood that your code is launch on keypress.
This imply that your RegEx have to match partial input or empty input.
This mean that your RegEx must match:
C++
'' // Empty textbox
'+' // + sign
'9' // a single digit
'+9' // + and a single digit
'9...9'  // many digits
'+9...9'

You need to rethink your RegEx, and probably check the full input at the end since the keypress can't enforce a minimum number of digits.

By the way * is for 'zero or more' RegEx sign, you need to use 'zero or 1' RegEx sign.

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx:
Regexper[^]
 
Share this answer
 
Comments
Member 13951173 23-Aug-18 3:34am    
Means I just replace the * to ? only
Patrice T 23-Aug-18 7:28am    
to make the + optional, yes, but your RegEx have more problems.
Use the Debuggex link to get a graph of your RegEx and see what is wrong.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900