I have an input field that should only accept characters used in a currency syntax (dollar sign, numbers, commas, and decimals). How can I write my REGEX to check if a string contains atleast one character that is NOT from the above listed characters?
I've tried the following, but the problem with this expression is that if one valid character is present in the string it throws the 'else' statement. (unitPriceVal is the user input string)
I want to write a regex that checks if the WHOLE string consists of the valid Currency, if true run the else statement
validCurrency = /([0-9\$.,])/;
if (!unitPriceVal.match(validCurrency) || unitPriceVal == "") {
unitPrice.setValueState("Error");
} else {
unitPrice.setValueState("None");
}
},
I want to write a regex that checks if the WHOLE string consists of the valid Currency
To check the whole string, anchor the match to the beginning and end of the input, using ^ and $, and make sure what's in between is a sequence (+) of allowable characters:
/^[\d$.,]+$/;
You don't need parentheses. You also don't need to escape the $ inside the character set. Finally, you can use \d for a digit.
Often, it's better to use the input element's pattern attribute to do this check. In that case, you don't need the anchors (they're implied):
<input pattern="[\d$.,]+">
How can I write my REGEX to check if a string contains at least one
character that is NOT from the above listed characters?
function validUnitPrice(unitPriceVal) {
let invalidCurrency = /[^0-9\$.,]/;
return unitPriceVal.search(invalidCurrency) == -1;
}
The ^ character as the first character inside a character set ([^...]) negates the character set i.e. matching characters not in the set.
Related
I want a Regex for my mongoose schema to test if a username contains only letters, numbers and underscore, dash or dot. What I got so far is
/[a-zA-Z0-9-_.]/
but somehow it lets pass everything.
Your regex is set to match a string if it contains ANY of the contained characters, but it doesn't make sure that the string is composed entirely of those characters.
For example, /[a-zA-Z0-9-_.]/.test("a&") returns true, because the string contains the letter a, regardless of the fact that it also includes &.
To make sure all characters are one of your desired characters, use a regex that matches the beginning of the string ^, then your desired characters followed by a quantifier + (a plus means one or more of the previous set, a * would mean zero or more), then end of string $. So:
const reg = /^[a-zA-Z0-9-_.]+$/
console.log(reg.test("")) // false
console.log(reg.test("I-am_valid.")) // true
console.log(reg.test("I-am_not&")) // false
Try like this with start(^) and end($),
^[a-zA-Z0-9-_.]+$
See demo : https://regex101.com/r/6v0nNT/3
/^([a-zA-Z0-9]|[-_\.])*$/
This regex should work.
^ matches at the beginning of the string. $ matches at the end of the string. This means it checks for the entire string.
The * allows it to match any number of characters or sequences of characters. This is required to match the entire password.
Now the parentheses are required for this as there is a | (or) used here. The first stretch was something you already included, and it is for capital/lowercase letters, and numbers. The second area of brackets are used for the other characters. The . must be escaped with a backslash, as it is a reserved character in regex, used for denoting that something can be any character.
^([a-zA-Z0-9]+[._-]?)+[a-zA-Z0-9]+$
I have used above regex to perform validation on input string for below scenarios.
I want to allow only hyphen ('-'), period ('.') & underscore ('_')
name should not start or end with hyphen ('-'), period ('.') & underscore ('_')
name should not contain Spaces
Two consecutive special characters (from set of (._-)) are not allowed
And I have validated it through javascript.
But, when we add name having special characters at the end, browser halts/ hangs instead of returning false.
var regex = new RegExp("^([a-zA-Z0-9]+[._-]?)+[a-zA-Z0-9]+$");
if (regex.test($('#txtBox1').val())) {//success}
Don't make those special delimiters optional in your repeated group:
^([a-zA-Z0-9]+[._-])*[a-zA-Z0-9]+$
# ^ ^
That still matches the same, but it can't backtrack to apply the optional character in positions where it doesn't appear.
Try this as well
var isValid = !!str.match(/[^\w.-]/i)
&& !str.split(/[._-]/).filter( s => s.length == 0 ).length;
Explanation
str.match(/[^\w.-]/i) checks if there is any character matching which is neither alphanumeric, underscore, dot nor hypen.
str.split(/[._-]/) splits the input by these three characters [._-] and then check if there is any empty string. If these characters are at the beginning or end or consecutively placed, then there will be an empty string in the resultant array.
Problem: I'm trying to validate when the user only inputted special characters without typing any number with it.
I'm using this expression
/^\+?[0-9 \.-]+$/
to accept only '+' sign, numbers, dots, hypens, and spaces when validating fax. This is working fine.
But with that expression the user can input -------------- without typing any number and is accepted because it contains hypen.
Question: Is there's a way to check if the input contains number? not just all special characters?
UPDATE:
This is an example of valid accepted input.
+1-2 12-98765.43 > the requirement is it should only accept '+' sign, hypen, numbers, spaces and dots.
Probably the easiest option is to have additional regex checks for each condition. E.g. have a regex check for just the presence of numbers /[0-9]/ and another check for just the presence of special characters /[ +.-]/. Run these only after testing that nothing undesirable exists in the string.
var whole = /^\+?[0-9 \.-]+$/
function validate(input) {
// input only contains valid things
if (!input.test(whole)) { return "Input must contain only numbers, spaces, and + . or -"; }
// input contains each required thing
if (!input.test(/[0-9]/)) { return "Number required"; }
if (!input.test(/[ .-]/)) { return "Special character required"; }
// You can also test the first character of the string with charAt()
if (input.charAt(0) !== "+") { return "Input does not begin with +"; }
return "Valid input";
}
I notice that your regex tests for zero or one plus, followed by a character in the list [numbers, spaces, periods, or hyphens]. Do you mean to test for any number of pluses? The regex I've posted (/[ +.-]/) should work for all the characters you want to allow.
I'm not sure this is what you're looking for, but if you want to verify that a specific single character or pattern exists in a string, you can use indexOf:
// Require at least one hyphen
if (input.indexOf("-") === -1) { return "Please include a hyphen"; }
Update: If, as in your example, there is only one plus and it is at the beginning, then you do indeed want the \+? bit. However, you don't need to escape the period inside of square brackets. Supposing the plus were required, you could use charAt to test this. See updated example.
Just add a lookahead.
^(?=.*[0-9])\+?[0-9 \.-]+$
See demo.
https://regex101.com/r/eB8xU8/9
This is an example of valid accepted input.
+1-2 12-98765.43 > the requirement is it should only accept '+' sign, hypen, numbers, spaces
Accepted input appear to accept . character as well ?
Try ^(\+\d-\d \d{2}-\d+)(?:\.\d+|$)
<form>
<input type="text" pattern="^(\+\d-\d \d{2}-\d+)(?:\.\d+|$)" required />
<input type="submit" />
</form>
I want to validate a string in JavaScript to allow alphanumerics, "(", ")" , and spaces. So test strings are:
s1 = "This $h00l*&^ not w0rk342*_(&, <and> always fail"
s2 = "This should work (ABC1234)"
my code:
var regX = new RegExp(/A-Za-z0-9\\(\\)\\x20+/);
if(!regX.test(s1)){
alert("InValid value.");
}
But it fails for both the strings.
Also as test() function evaluates the matches in the string and not the whole string
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
Can someone please help. Thanks in advance
You should use this regex:
/^[A-Za-z0-9() ]*$/
Replace * with + if you don't want to allow empty string.
^ and $ test for beginning and the end of the string respectively.
* means repeat 0 or more times. + means repeat once or more.
To specify a character class (i.e. a set of character), you need to place the characters inside [].
To further shorten the regex:
/^[a-z\d() ]*$/i
i flag will make the regex matches case-insensitively, which remove the needs to specify A-Z.
\d is the shorthand character class for digits 0-9. Shorthand character class can also be included inside character class.
I want to check if a text box input is valid (only alphabet, numbers and underscores allowed. No whitespaces or dashes). I currently have this, but whitespaces & dashes seem to pass.
function validText(field)
{
var re = /[a-zA-Z0-9\-\_]$/
if (field.value.search(re) == -1)
{
alert ("Invalid Text");
return false;
}
}
A valid input would be something like
'Valid_Input123'
invalid
'Invalid-Input !'
The \w is a handy regex escape sequence that covers letters, numbers and the underscore character
You should test the entire string for valid characters by anchoring the validity test at the start (^) and end ($) of the expression
The regular expression test method is faster than the string search method
You can also test for one or more characters using the + quantifier
To summarise (in code)
var re = /^\w+$/;
if (!re.test(field.value)) {
alert('Invalid Text');
return false;
}
return true;
Alternatively, you can test for any invalid characters using
/\W/.test(field.value)
\W being any character other than letters, numbers or the underscore character.
Then you might also need to add a length check to invalidate empty strings, eg
if (/\W/.test(field.value) || field.value.length === 0)
You are only testing whether the text ends ($) with one of the characters in the character class. You are also explicitly allowing a dash (\-). If you don't want that, remove it.
Anchor the expression (^, $), add a quantifier (+) and .test whether the string only consists of those characters:
var re = /^[a-zA-Z0-9_]+$/; // or /^\w+$/ as mentioned
if (!re.test(field.value)) {
}
You forgot to anchor your regex at the beginning using ^
test is easier to use
There is no need for the dash.
It should look like this:
if (!/^[a-z0-9_]+$/i.test(field.value)) {
//
}
[\w]* will suffice.
Regex101 Example
This is a very basic Regular Expressions question
Learn more about regular expressions here: regular-expressions.info