I'm looking to check that the first two characters entered in a name field are letters--beyond that it makes no difference (spaces, ', -, etc are all fair game). Here's what I have so far, but it isn't working. Thoughts? Thanks!
if (document.form01.firstName.value.length < 2
|| !/^[a-zA-Z]{2}+.?$/.test(document.form01.firstName.value)) {
alert("First name must contain at least 2 letters.");
document.form01.firstName.select();
document.form01.firstName.style.backgroundColor="yellow";
return false; // leave now
}
Your expression has what appears to be a syntax error. The + doesn't have anything to require one-or-more of, and JS doesn't do super-greedy matches -- it supports ? following a quantifier to make the expression ungreedy, but not +. You should be getting a SyntaxError or the like. (If you're not, the browser might be interpreting the + literally and expecting a +.)
You could change the expression to /^[a-zA-Z]{2}.?$/ to get rid of that error...but note also that it won't match if there's punctuation within the string -- it'll only match a single non-letter at the end.
You'd do better to only try to match what you care about. In this case, since you only care that the first two characters are letters, /^[a-zA-Z]{2}/ would avoid the issue entirely.
function digitVal(elem){
if (!elem.value.match(/\d{2,2}/)){
// if the first two characters are not digits
elem.style.background = 'yellow';
// the background changes to yellow
}
else {
elem.style.background = 'white';
// otherwise leave it white
}
}
<input type="text" onkeyup="digitVal(this)" size="40" placeholder="first two characters must be numbers"/>
Related
I've written a basic 2 operand calculator app (+ - * /) that uses a couple of inline regex validations to filter away invalid characters as they are typed.
An example looks like:
//check if operator is present
if(/[+\-*\/]/.test(display1.textContent)){
//validate the string each time a new character is added
if(!/^\d+\.?\d*[+\-*\/]?\d*\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
//validate the string character by character before operator
} else {
if(!/^\d+\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
}
In the above, a valid character doesn't return false:
23.4x0.00025 (no false returned and hence the string is typed out)
But, if an invalid character is typed the function returns false and the input is filtered away:
23.4x0.(x) x at the end returns a false so is filtered (only one operator allowed per calculation)
23.4x0. is typed
It works pretty well but allows for the following which I would like to deal with:
2.+.1
I would prefer 2.0+0.1
My regex would need an if-then-else conditional stating that if the current character is '.' then the next character must be a number else the next char can be number|.|operator. Or if the current character is [+-*/] then the next character must be a number, else the next char can be any char (while following the overall logic).
The tricky part is that the logic must process the string as it is typed character by character and validate at each addition (and be accurate), not at the end when the string is complete.
if-then-else regex is not supported in JavaScript (which I think would satisfy my needs) so I need to use another approach whilst remaining within the JS domain.
Any suggestions about this specific problem would be really helpful.
Thanks
https://github.com/jdineley/Project-calculator
Thanks #trincot for the tips using capturing groups and look around. This helped me write what I needed:
https://regex101.com/r/khUd8H/1
git hub app is updated and works as desired. Now just need to make it pretty!
For ensuring that an operator is not allowed when the preceding number ended in a point, you can insert a positive look behind in your regex that requires the character before an operator to always be a digit: (?<=\d)
Demo:
const validate = s => /^(\d+(\.\d*)?((?<=\d)[+*/-]|$))*$/.test(s);
document.querySelector("input").addEventListener("input", function () {
this.style.backgroundColor = validate(this.value) ? "" : "orange";
});
Input: <input>
I'am trying to allow following pattern for a single html input box with javascript regex
-int (aka any minus number so long it not followed by a zero and is in the first position)
0 (a single zero is allowed)
int (is allowed)
I use this function the remove anything that doesn't match it
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
which doesn't work.
Other examples is:
/[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. It allows minus everywhere in the string
(/^((?!:([1-9-]?[0-9])).)/g Don't allow none.
[^1-9-]?[^0-9]* Allow all...
I think I'am missing something.. Any suggestions would be most appreciated..
You may try this regex
^(0).*|^(-?)([1-9]\d*)?.*|^.*
and replace it with $1$2$3 after input
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />
It has three tests:
^(0).* // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.* // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.* // if previous rules are not matched, discard everything
In short:
generally only -, 0-9 are allowed.
if you type a 0 first, nothing will be allowed after.
if you type a 1-9 first, only numbers are allowed after.
if you type a - first, only 1-9 is allowed next, then any digit is allowed after.
I changed your regexp and made it a bit more modular and it worked fine.
function toValidNumber(int) {
return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}
$('.dointcheck').live('keyup',
function () {
$(this).val(toValidNumber($(this).val()));
});
Orginal RegEXP in Stackoverflow
Not able to match the regular expression in my JavaScript code which I have written for form validation.
I wanted to validate my form field which is password using RegExp [[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]
My Validations on password is
- Should contain 10 characters including digit
- At least one uppercase letter should be there
- Only # should be used as special character
But the same is working with [0-9a-zA-Z#]{10} but not with [[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]
var regexpassword=/[[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]/
if(!regexpassword.test(password.value)){
alert("Enter valid password")
password.focus();
return false
}
NOTE: The password that I have entered is Welcome#67
It should not give the alert as "Enter valid password"
Best I can tell, the regex you provided, is matching exactly 1 character. the [] operator indicates "any of what is inside". But the only place you are indicating "multiple times" is the [A-Z]{1,8}. Also, as #Pointy mentioned, I don't think you can nest square brackets. Even if you can, it is somewhat redundant.
Your regex is being interpreted as follows:
1. Look for [ or the numbers 0 through 9 between 0 and 8 times in a row
2. Followed precisely by the lowercase letters a through z between 0 and 8 times in a row
3. Followed precisely by the uppercase letters A through Z between 1 and 8 times in a row
4. Followed precisely by a single #
5. Followed precisely by a single ]
This leads to matching strings like (but not limited to):
[A#]
0A#]
9aaaaaaaZ#]
[0123456abcdefghABCDEFGH#]
[[[[[[[[Q#]
[[[[[[[[azazazazAZAZAZAZ#]
but it will not match Welcome#67.
Is there a way to write a regex that will validate a password with your requirements?
Possibly.
Should you use a single regex to validate your password?
Probably not as the necessary complexity of that regex would make it impractical to maintain when your password requirements change.
Is there a practical, maintainable way to validate passwords?
Certainly! Use multiple regexes to validate the required parts of the password.
Then determine if the needed parts are present and make sure the length is acceptable.
Example:
var hasOnlyValidCharacters = /^[0-9a-zA-Z#]+$/gm.test(password.value);
var hasDigits = /[0-9]+/gm.test(password.value);
var hasUpper = /[A-Z]+/gm.test(password.value);
var hasLower = /[a-z]+/gm.test(password.value);
var hasAtSign = /[#]+/gm.test(password.value); // Technically could be /#+/gm.test(...), but I tend to use character classes every time I'm looking for specific characters.
var isValidPassword = (
password.value.length === 10 // Should contain 10 characters
&& hasOnlyValidCharacters
&& hasDigits // including digit
&& hasUpper // At least one uppercase letter should be there
// && hasLower // Uncomment to require at least one lowercase letter
// && hasAtSign // Uncomment to require at least one #
);
if (!isValidPassword) {
alert("Enter valid password")
password.focus();
return false
}
The [untested code] above should do the trick, and following the patterns established in it, you should be able to easily change your password requirements on a whim.
So I'm posting due to me having spent several hours working on a filter that should record only certain chat messages based on the start of said message. I've reached a point where it's about fifty-fifty, but my lack of knowledge regarding regex has stopped me from being able to continue working on it.
Basically, the expression is supposed to match with messages that are one of a few annoying things. My apologies if this gets too specific, I'm unsure of how to get all of the conditions working together.
"word": (any word that is not "notice" or "type: s" - So anything like John:
word_word: (this time, the second word can be anything) - Something like John_Smith:
[Tag]word: or [Tag]word_word: (where a tag is either a unicode character or two characters between square brackets) - Something like [DM]Tom_Cruise: or such
One of the above, minus the colon. This is where I'm having issues. Something like [DM]Tom_Cruise waves.
Starts with (WHISPER) or (SHOUT). It doesn't matter what comes after it, in this case.
I've managed to get a regex that works with most of the situations, but I can't get condition 4 to work without getting unwanted messages.
In addition, if the message (received as a string per line) starts with (OOC), it shouldn't be matched. If it says (OOC) in the message later on, it's alright. If the string ends with "joined the game." or "left the game.", it should also not match.
So... yeah, I'm completely stuck on getting condition 4 to work, and hoped that the community that helped me get this far wouldn't mind answering a (hopefully not too specific) question about it. Here's the expression as I've gotten it:
(?!^\(OOC\))(_[a-z]+:)|(^[a-z]+:)|(^[a-z]+ [a-z]+ )
It can match most of the above conditions, except for 4 and some of 1. I can't figure out how to get the specific words (notice: and type:s) to not match, and 4 is just messing up some of my other conditions. And lastly, it doesn't seem to stop matches if, despite starting with (OOC), the string matches another condition.
Sorry if this is too specific, but I'm completely stuck and basically just picked up regex today. I'll take anything.
EDIT
Examples:
[AT]Smith_Johnson: "Hello there." - matches under Condition 3, works
Tom_Johnson: moves to the side. - matches under Condition 2, works
Notice: That private wooden door is locked. - should not match due to Condition 1, but currently does
Tom hops around like a fool. - Should match under Condition 4, doesn't
(OOC)SmithsonsFriend: hey guys, back - matches, but shouldn't under the not-match specifiers
(WHISPER)Bob_Ross: "Man, this is lame." - Condition 5
West Coast: This is a lovely place to live. - doesn't match due to whitespace, that's good
Joe joined the game. - matches, shouldn't under the not-match specifiers
EDIT TWO
To clarify:
A) string starts with (OOC) - never match
B) string starts with (WHISPER) or (SHOUT) - always match
If neither A nor B apply, then go to conditions 1-4.
You can use this regular expression:
^(?:\(shouts\)|\(whisper\))?(?:\[[A-Z]{1,2}\])?(?!Notice|Note)[A-Za-z]*(?:_[A-Za-z]*)?(?::|\s(?![A-Za-z]*:))(?!(?:joined|left) the game)
^ Start of the string (make sure to check line by line)
(?:\(shouts\)|\(whisper\))? allows optional sequences like (shouts) or (whisper)
(?:\[[A-Z]{1,2}\])? matches a non-capturing group with 1 or 2 A-Z characters inside [] which is optional (because of the ? at the end)
(?!Notice|Note): list of words, which are not part of the subsequent selector
[A-Za-z]* matches as much alphabetical characters as possible
(?:_[A-Za-z]*)? matches a _ followed by alphabetic characters
(?::|\s(?![A-Za-z]*:)) matches a : or a whitespace character \s, which however cannot be followed by [A-Z]:
(?!(?:joined|left) the game) negative lookahead: whole regex does not match, if this pattern matches
You should add the case insensitive flag /i in your regex, if you want to e.g. match (whisper) and (WHISPER).
→ Here are your example texts in an updated regex101 for a live test
Instead of making it one big (HUGE) regular expression, you could make a function that take a message and then check it against a number of regular expression (much flexible and much easier to implement). Like this:
function isValid(msg){
// starts with "WHISPER" or "SHOUT"
if(/^(?:whisper|shout)/i.test(msg)) return true;
// Check if it begins with "notice:" or "type:"
if(/^(?:notice|type)\s*:/i.test(msg)) return false;
// Check if it ends with "joined the game" or "left the game."
if(/(?:joined|left)\s+the\s+game\.?$/i.test(msg)) return false;
// starts with "(ooc)"
if(/^\(ooc\)/i.test(msg)) return false;
// "[at]word:" or "[a]word_word" or "word:" or "word_word" ...
if(/^(?:\[[a-z]{1,2}\])?[a-z_]+:?.*$/i.test(msg)) return true;
return false;
}
Example:
function isValid(msg) {
if (/^(?:whisper|shout)/i.test(msg)) return true;
if (/^(?:notice|type)\s*:/i.test(msg)) return false;
if (/(?:joined|left)\s+the\s+game\.?$/i.test(msg)) return false;
if (/^\(ooc\)/i.test(msg)) return false;
if (/^(?:\[[a-z]{1,2}\])?[a-z_]+:?.*$/i.test(msg)) return true;
return false;
}
function check() {
var string = prompt("Enter a message: ");
if(isValid(string))
alert(string + " is valid!");
else
alert(string + " is not valid!");
}
<button onclick="check()">TRY</button>
I need a regex to use with javascript/jquery that fits these rules...
it will include 10 digits
if there is a leading 1 or +1 it should be ignored
valid characters allowed in the field are... 0-9,(), and -
I found a regex at Snipplr (the first one), but its not working. First of all, I'm not even sure if that regex fits my rules. Secondly, its allowing inputs like &^%$$#%^adfafsd. I believe the error is in my code not the regex. For example, are there supposed to be quotes around the expression?
Here is the code that is supposed to be validating the phone field...
$('#phone').bind('blur', function() {
var pattern = new RegExp("^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$");
if(pattern.test($('#phone').val())){
$("#phone").addClass("error");
return false;
}else{
$("#phone").removeClass("error");
return true;
}
return true;
})
When you're not using the literal form ( /[regex]/ ), you need to escape the regex string. Try this instead:
var regex = /^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/;
if(regex.test($('#phone').val()){ ... }
if there is a leading 1 or +1 it should be ignored
it will include 10 digits
valid characters allowed in the field are... 0-9,(), and -
That could be matched with an expression like:
/^(?:\+?1)?[()-]*(?:\d[()-]*){10}$/