Using regex to validate in JSP [duplicate] - javascript

This question already has answers here:
Validating javascript decimal numbers
(5 answers)
Closed 8 years ago.
I have an input field and I want to validate its content before passing the value further. I'm struggling with creating a proper regex though, as regex created in online editor doesn't really work with my code (actually it blocks everything).
Desired regex behaviour:
Only numbers and ., you can use . only once as a decimal separator, value cannot start/end with ., value cannot start with 0.
My code:
var valueInput = $(row).find("#value").val();
var numbers = /^[0-9.]*$/;
if( !valueInput.match(numbers) ) {
//do something
}
valueInput is fine, it brins the value from the input properly. Any ideas?
Edit.
Thanks for your contribution, I wanted to sum up a little for people from future, looking for an answer:
1. Regex is not a string! I edited former code to make sure nobody's get confused, but comment to get rid of " " was crucial, thanks Pointy.
2. Regex I decided to use is /^([1-9][0-9]*)+(?:\.\d+)?$/. I realized I also need to handle case, when value has only decimal part, so it starts with 0. I didn't really want to play with regex here, so I made a trick: if valueInput start with something other than zero I validate with , else I validate with /^[0]{1,1}\.\d{1,2}$/g.

/[1-9](\d+)?(\.\d+[1-9])?/
This is the best I could come up with. If this doesn't work, do let me know.
P.S. I find regexr a nice place to test regex. Cheers.

I'd do this:
valueInput.match(/([1-9]d*)+(?:\.\d+)?$/)

Related

Validating client-side data input using a pattern

I am currently working on a project whereby data can be added into a database via a website. Currently I have managed to configure it so that the form accepts title, postcode, vehicle reg and ID number.
Javascript validation is working fine for these entries, with the exception of ID number. All ID numbers are a specific format (2 numbers followed by a . followed by 4 numbers).
I cannot seem to work out how to define the pattern.
Due to the size of my code, I have not posted the full code here (all is validating except this ID validation), but I've provided a snip of the 'if' statement below which I'm trying to come up with.
if (inputElement.id == "wid") {
pattern = /^[a-zA-Z0-9 ]*$/;
feedback = "Only 2 numbers followed by a . followed by 4 numbers are
permitted";
I know that the pattern isn't correct here but I have searched for hours trying to locate some easy to explain guidance and cannot find anything which appears to be relevant.
Any thoughts would be appreciated.
Thank you
You can try out something like https://regex101.com/ to test you regexes, and see an explanation of it.
I think your pattern should be this: /^[0-9]{2}\.[0-9]{4}$/.
The first part ([0-9]{2}) makes sure that the id starts with 2 digits, then a dot \. (which must be escaped, because it means "every character" otherwise) and then 4 digits [0-9]{4}

Remove everything before the first forward slash in the url [duplicate]

This question already has answers here:
How do I parse a URL into hostname and path in javascript?
(26 answers)
Closed 2 years ago.
I need to remove everything before the third forward using regex so that for example https://stackoverflow.com/questions/ask becomes /questions/ask I'm not the greatest when it comes to regular expressions so your help would be much appreciated.
This is what I have so far https://regex101.com/r/qQ2dE4/498
The code I currently have is but want to use regex:
url.substring(url.indexOf('\/') + 3)
Use this:
(?<=.*\/.*\/.*\/).+
Demo
Explanation:
(?<= - its positive look behind, in any position that's pattern inside it is find matching start from this position to forward.
.*\/.*\/.*\/ - it is used inside the positive look behind, it cause matching start after the position that behind that position is 3 forward slashes
.+ - match one or more of from anything
Edit:
From #JaromandaX's comment, this can also be used (and honestly I think it more readable and simper):
(?<=(?:.*?\/){3}).+
I understand the questions asks for regex but the need is unclear - if all you need is the path name there are better tools in the toolbox (for anybody not working on a homework exercise).
const url = 'https://stackoverflow.com/questions/ask'
console.log(new URL(url).pathname)

Regex to match date with string as month

I have the following string:
var cur = "t+20d";
And I want to match it. That part I already did with
if(cur.match(/^[t]\+[0-9]{2,4}[dmyw]/i))
Now I also need to be able to match this string, and prefably in the same regex
var cur = "10may15+20d";
I have tried
cur.match(/^([t]|([0-9]{1,2}(jan|feb|march|apr|may|jun|jul|aug|sept|okt|nov|dec)))\+[0-9]{2,4}[dmyw]/i)
But it doens't work as intended.
if I try to compile the subpart I get two pieces of array instead of one
cur.match(/[0-9]{1,2}(jan|feb|march|apr|may|jun|jul|aug|sept|okt|nov|dec)/i);
//yields ["10MaY", "MaY"]
And this worries me about false positives.
I'm really really rusty at regex, last time I tried to make a complicated regex was 15 years ago and that was in perl, so I could really use some help with this one. I know ors and grouped matches are possible, I just can't figure out how to do it anymore so some help is appriciated.
You need to match the number which exists after the month.
^(t|[0-9]{1,2}(?:jan|feb|march|apr|may|jun|jul|aug|sept|okt|nov|dec)\d+)\+[0-9]{2,4}[dmyw]
DEMO
With the help of #AvinashRaj who pointed me to the group operator ?: with his regex I managed to compose this regexfor my uses and i'm posting it here for future users who might need to match a date string like this. ddmmmyy
cur = "10-apr-1115+20d";
cur.match(/^(?:t|[0-9]{1,2}(?:jan|feb|mar|apr|may|jun|jul|aug|sep|okt|nov|dec|[-\/](?:[0-9]{1,2}|jan|feb|mar|apr|may|jun|jul|aug|sep|okt|nov|dec)[-\/])(?:[0-9]{2}|[0-9]{4}))\+[0-9]{1,4}[dmyw]/igm);

replace all but - ,+, and .

I'm working on a donation webapp, and I need to format a string the will leave minuses (-), pluses (+), and decimals (.). I want people to be able to format their dollar amounts how they want, but leave the numbers and decimals as is.
I currently have the following code:
var raised = $('#raised').val().replace(/\D/g,'');
Any help? Thanks!
UPDATE
Let me explain a little more about why this is an easy/quick way to validate the input.
This is going to be something that administration is going to use one time only, with only one person in charge. It's not going to be something where multiple users input to submit actual money. I agree that this could be much better planned, but this is more of a rush job. In fact, showing you what I have done is going to be the quickest way to show you: http://www.cirkut.net/sub/batterydonate-pureCSS/
This is going to be projected during an event/auction so people kind of have an idea of how much money has been donated.
The person in charge of typing in donations is competent enough to type valid inputs, so I was putting together what I could as quickly as possible (the entire thing needs to be done by noon tomorrow).
But anyways I found what I needed. Thanks a lot everyone!
To do exactly what you're asking, you could use this regex:
var raised = $('#raised').val().replace(/[^-+.\d]/g,'');
But be advised, you'll still need to verify that the returned string is a valid number, because strings like '---' and '+++' will pass. This, perhaps, is not even something you want to do on the client-side.
Try the following regex:
.replace(/[^\d\-+\.]/g, '')
Since this doesn't guarantee you have a valid number and not something like +-12.34.56--1, You can then validate that you have a valid number with something like:
/^[-+]?\d+(\.\d+)?$/
A regular expression character class can be negated by adding a ^ symbol to the beginning.
In your case, this makes it fairly simple: you could add all the characters you want to keep in a character class and negate it.
var raised = $('#raised').val().replace(/[^\d\.\+\-]/g,'');
Hope that helps.

Check that the user is entering a time format? eg 13:00

Basically, I'd like to have an input that when blur'd, will check the input to make sure it's in the format...
[24hour] : [minutes]
So for example 13:00, or 15:30.
So I guess I have to split it up into three parts, check the first bit is between 0 and 24, then check it has the semi-colon, then check it has a number between 0 and 60.
Going more complicated than that, it'd be fantastic to have it so if the user enters 19 it'll complete it as 19:00 for example.
I am using jQuery fwiw, but regular code is fine, for example I'm using this little piece of code so far which works fine, to convert . inputs to :
tempval = $(this).val().replace(".", ":");
$(this).val(tempval);
Not sure where to start with this, if anyone could recommend me some reading that'd be fantastic, thank you!
([0-1 ]?[0-9]|2[0-3]):([0-5][0-9])
I think that's the regex you're looking for (not specifically for javascript though).
http://www.regular-expressions.info/
This site has an excellent amount of info for language-specific regular expressions! Cheers!
I suggest using masked input That way the wrong input will be prevented in the first place.
Disclaimer: I haven't used that plugin myself, just found it by keywords "masked input"
There are a bunch of widgets that already deal with time validation - try googling for "jQuery time widget" - the first result doesn't look bad.
var re = /^(\d+)(:\d+)?$/;
var match = re.match(yourstring);
Now if the match has succeeded match is an array with the matched pieces: match[0] is the whole of yourstring (you don't care about that), match[1] has the digits before the colon (if any colon, else just digits), match[2] if it exists has the colon followed by the digits after it. So now you just need to perform your numeric tests on match[1], and possibly match[2] minus the leading colon, to ensure the numbers are correct.

Categories

Resources