How do I exclude a given set of numbers from a RegEx? - javascript

I have this piece of code:
$('.numeric-year').keyup(function () {
$(this).toggleClass('field-error', /10|11|12/.test(this.value));
});
What I'd like to do is exclude a given set of numbers(e.g 10, 11, 12) from triggering the .toggleClass() function.
This question is solely to do with RegEx as the rest of the code is working. Sorry I'm terrible at RegEx stuff...learning slowly.
Any help would greatly be appreciated, Thanks

This particular case would probably be better served using a conditional based on $(this).value.
Regular expressions are a pattern matching service. If you want to check whether $x follows a specific pattern, use regexp. In your case, though, you're trying to check whether the value of a given string is equal to one of a couple values. While this could be accomplished using regexp (as bliof said, check for the presence of 1[0-2], and if true, don't run), that's a bad habit to get into... that is the job for a string comparison tool, not regex. It be possible, but it's going to be more kludgy, and in other situations this type of thinking may lead to a lot of problems and head-scratching. I would just use
$(this).value() != 10 || $(this).value() != 11 || $(this).value() != 12
Based on your reply, I would still not recommend regex, but the .inArray() construct, which is more appropriate for your situation.

After having a stab at it myself I came up with this solution
$(this).toggleClass('field-error', !/10|11|12/.test(this.value));
based on Justin Poliey's answer( Regular Expression to exclude set of Keywords ) telling me NOT to negate in the RegEx but in my code.
Hence the ! before the regex /10|11|12/ and it worked a charm. Thanks for your effort guys...Much Appreciated

You can try using positive or negative lookahead.
Lets say that you have 3 input fields:
<input type="text" value="2020" />
<input type="text" value="2010" />
<input type="text" value="2000" />
And you want to get the elements with different value than 2010 and 2000, you can do something like this:
$("input").filter(function() {
if(!this.value.match("(?=2010|2000)")) {
return this;
}
});

Related

How do i allow only one (dash or dot or underscore) in a user form input using regular expression in javascript?

I'm trying to implement a username form validation in javascript where the username
can't start with numbers
can't have whitespaces
can't have any symbols but only One dot or One underscore or One dash
example of a valid username: the_user-one.123
example of invalid username: 1----- user
i've been trying to implement this for awhile but i couldn't figure out how to have only one of each allowed symbol:-
const usernameValidation = /(?=^[\w.-]+$)^\D/g
console.log(usernameValidation.test('1username')) //false
console.log(usernameValidation.test('username-One')) //true
How about using a negative lookahead at the start:
^(?!\d|.*?([_.-]).*\1)[\w.-]+$
This will check if the string
neither starts with digit
nor contains two [_.-] by use of capture and backreference
See this demo at regex101 (more explanation on the right side)
Preface: Due to my severe carelessness, I assumed the context was usage of the HTML pattern attribute instead of JavaScript input validation. I leave this answer here for posterity in case anyone really wants to do this with regex.
Although regex does have functionality to represent a pattern occuring consecutively within a certain number of times (via {<lower-bound>,<upper-bound>}), I'm not aware of regex having "elegant" functionality to enforce a set of patterns each occuring within a range of number of times but in any order and with other patterns possibly in between.
Some workarounds I can think of:
Make a regex that allows for one of each permutation of ordering of special characters (note: newlines added for readability):
^(?:
(?:(?:(?:[A-Za-z][A-Za-z0-9]*\.?)|\.)[A-Za-z0-9]*-?[A-Za-z0-9]*_?)|
(?:(?:(?:[A-Za-z][A-Za-z0-9]*\.?)|\.)[A-Za-z0-9]*_?[A-Za-z0-9]*-?)|
(?:(?:(?:[A-Za-z][A-Za-z0-9]*-?)|-)[A-Za-z0-9]*\.?[A-Za-z0-9]*_?)|
(?:(?:(?:[A-Za-z][A-Za-z0-9]*-?)|-)[A-Za-z0-9]*_?[A-Za-z0-9]*\.?)|
(?:(?:(?:[A-Za-z][A-Za-z0-9]*_?)|_)[A-Za-z0-9]*\.?[A-Za-z0-9]*-?)|
(?:(?:(?:[A-Za-z][A-Za-z0-9]*_?)|_)[A-Za-z0-9]*-?[A-Za-z0-9]*\.?)
)[A-Za-z0-9]*$
Note that the above regex can be simplified if you don't want usernames to start with special characters either.
Friendly reminder to also make sure you use the HTML attributes to enforce a minimum and maximum input character length where appropriate.
If you feel that regex isn't well suited to your use-case, know that you can do custom validation logic using javascript, which gives you much more control and can be much more readable compared to regex, but may require more lines of code to implement. Seeing the regex above, I would personally seriously consider the custom javascript route.
Note: I find https://regex101.com/ very helpful in learning, writing, and testing regex. Make sure to set the "flavour" to "JavaScript" in your case.
I have to admit that Bobble bubble's solution is the better fit. Here ia a comparison of the different cases:
console.log("Comparison between mine and Bobble Bubble's solution:\n\nusername mine,BobbleBubble");
["valid-usrId1","1nvalidUsrId","An0therVal1d-One","inva-lid.userId","anot-her.one","test.-case"].forEach(u=>console.log(u.padEnd(20," "),chck(u)));
function chck(s){
return [!!s.match(/^[a-zA-Z][a-zA-Z0-9._-]*$/) && ( s.match(/[._-]/g) || []).length<2, // mine
!!s.match(/^(?!\d|.*?([_.-]).*\1)[\w.-]+$/)].join(","); // Bobble bulle
}
The differences can be seen in the last three test cases.

Jquery Validate Plugin to allow only text

I'm using following jquery plugin
http://digitalbush.com/projects/masked-input-plugin/
my current script is
<script type="text/javascript" charset="utf-8">
$(document).ready(function($) {
$("#answer55937X1X3othertext").mask("aaaaaaaaaaaaaaaaaaaaaaaaa",{ placeholder:"#" });
});
</script>
Problem:
But actually I would like to allow user to enter text only of any number of characters. Ex: words, Phrases or even sentences. So I figured regex would be good fit.
Question 1:
Any idea how to implement regex in this plugin ? If not please suggest alternative.Please include regex code too.
Question 2:(out of curiosity)
I did look at the website but couldn't find anything related to regex. Is regex by default included in plugins ? I don't know how to check whether that feature is included or not.
Thanks in advance
Update:
I tried below script but it is not working.
$('question'+QQ' input.text').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
as far as I know, you can't do that using 'masked input', it doesn't support the requirement you want.
it would perfactly fit for those input that having "fixed length", e.g.
an input with 8 length: 010-55555 (phone numbers)
an input with 8 or 11 length: 086-010-55555 (another phone numbers)
it does not support this:
this is a sentence that doesn't have fixed words.
Since it has to first of all fullfil the input with place holder "#".
If you want to validate the input, just write your own customized functions, using Really simple validations or other jquery validation frameworks, or even your own:
<input id="your_field" />
<script>
$("#your_field").blur(function(){
// your implementation here....
$(this).val().match(...)
})
</script>
Why do you need to use the mask plugin if you want to allow the user to enter whatever they want?
Besides, after looking at the page, it doesn't look like the plugin accepts regular expressions (please correct me if I'm wrong). For example, they use the * character to represent any alphanumeric character. In regular expressions, the * character has special meaning.
Hello fellow stackoverflower! I've just spent 20 minutes or so designing a jquery plugin that I'm hoping you, as well as many others, will be able to implement for this input masking. Please keep in mind, this is very quick work, and I hope to add to it, but just let me know if it fulfills your needs!
https://github.com/bmoyles0117/jQuery-SimpleMask
Please feel free to try to implement it using the code below, "a" stands for alphabetical, "#" stands for alphanumeric including spaces, and "9" of course stands for numbers. What I've done, is add flags to the initial config to say whether or not you'd like to allow periods, commas, or dashes. I really hope this fulfills your need!
<script src="jquery.simplemask.js"></script>
<script type="text/javascript">
$(function() {
$('#test123').simpleMask('aaaaa-####999', {
allow_periods : true,
allow_commas : true,
allow_dashes : true
});
});
</script>
<input type="text" id="test123" />

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.

Jquery Plugin: ba-replacetext, Javascript working but needing help.. RegExp?

I am trying to remove text from a dropdown menu using a Jquery plugin called ba-replacetext. It's ALMOST working, but could use a bit of tweeking. Please help me out as I am still learning Jquery / JS programming. Thanks!
(trying to remove ONLY the following phrases: "less $2,800.00" and "less $200.00")
HTML Source:
<select id="ct100_mainContent_productOption_1000193123" name="optionId">
<option value="">- Select Deposit or Full Tuition -</option>
<option value="1000918521" selected="selected">Full Tuition (One Time Payment of $3,000)</option><option value="1000918519">Deposit Only ($200 Initial Payment) - less $2,800.00</option><option value="1000918520">Remaining Balance ($2,800 Following Deposit) - less $200.00</option></select>
Jquery Function:
$(function(){
$('#ct100_mainContent_productOption_1000193123').ready(function(){
$('#ct100_mainContent_productOption_1000193123 *').replaceText(/less \$(2,8|2)00\.00/gi, '');
$('#ct100_mainContent_productOption_1000193123 *').replaceText( /-+/gi, '' );
});
});
Result of this code is that only the word less is removed not the entire phrase less $2,800.00. I can't get it to work, perhaps because I am using the wrong Regexp? Thoughts? Many thanks!
If you want exactly "less $2,800.00" and "less $200.00" then you would need something along the lines of:
replaceText(/less \$(2,8|2)00\.00/gi, '')
Here the (2,80|2) will match either of the two variants above, but nothing else. If instead you want to match any for of money statement you would need:
replaceText(/less \$[0-9,.]+/gi, '')
Also, you will want to account for the "-" before your "less" since that will be dangling after replacement. Of course you will need to experiment with your exact needs for which I would recommend searching with terms "javascript regex" and find a reference that works best for you. Mine is w3schools.
u can use on all 'less' text globally ..
$('#ct100_mainContent_productOption_1000193123 option').each(function () {
var html = $(this).html();
var i = html.indexOf('less');
if (i > -1) {
$(this).html(html.substring(0, i));
}
});
Yup, your regex doesn't say anything about the dollar amount. \bless\b means "match a word boundary, then the word 'less', then another word boundary". You want something like \bless \$[0-9,.]+. You can test your regular expressions at sites like this, and it sounds like you might want to read an intro to regexes generally.
Small disclaimer: I don't know anything about ba-replacetext.

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