Cannot form regex expression - javascript

I have used the below regex expression to check alphabets, numbers, characters, + and -
if (/[^a-z0-9\-\+]+$/i.test(value))
{
alert ("Only alphabets and numbers are allowed.");
return;
}
This shows the message if any special characters is used. But one problem i am facing is if the value is a combination of special characters and alphabets or numbers then this condition does not satisfy. For example if the value is %$2 then the condition does not return true and show the message. I want that if any special character is present then the condition should satisfy and show the message.

You should not use the $ anchor. Also the final + is not necessary in your case. The following checks whether the string contains any disallowed characters:
if (/[^a-z0-9\-\+]/i.test(value))
{
alert ("Only alphabets and numbers are allowed.");
return;
}
You could also invert the condition. (Use * or + depending on whether you allow empty string.) The following checks whether the whole string only contains the allowed characters:
if (!/^[a-z0-9\-\+]*$/i.test(value))
{
alert ("Only alphabets and numbers are allowed.");
return;
}

$ Matches the end of string
and $ is not required in your case
+ matches previous token one or more times ,
and it is also not required in your case
if (/[^a-z0-9\-\+]/i.test(value))
{
alert ("Only alphabets and numbers are allowed.");
return;
}

Related

Regular expression not working for special character

I'm trying to create a regular expression for a field with the following conditions.
no blank should allowed
special characters are not allowed apart from underscore, hyphen, period.
Alphabets and numeric are allowed.
I have created my own regular expression its working fine but it is accepting one special character in the beginning
like if i enter # or $wer in the field it will work and data will be saved.
like if i enter ## , %^hihf or qwerty#333 in the field it will show an error.
find below code.
$.formUtils.addValidator({
name: "username",
validatorFunction: function(a) {
return !!a.match((/^[^\s][ A-Za-z0-9_./-]*$/))
},
errorMessage: "Please enter a valid Username (Special characters are not allowed apart from Underscore(_), Hyphen(-) and Period(.)) ",
errorMessageKey: "badname"
}),
I think you need more than just a Regex for some of these conditions. Try:
validatorFunction: function(a) {
var rgx = /^[A-Za-z0-9_./-]+$/;
var trimmed = a.trim();
return trimmed.length > 0 && rgx.test(trimmed);
}
This would solve the issues of blanks, special characters, and forcing alphanumerics...
Your [^\s] at the start of the regex means any character other than a space is valid, hence "#" will match.
I think you want to use something like this to allow leading and trailing whitespace and force at least 1 valid character:
return !!a.match((/^\s*[A-Za-z0-9_\./\-]+\s*$/))

How can I find one instance of a character using REGEX?

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.

Validate if input contains only special characters without any numbers with it

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>

Check password valid using regex in javascript

The password must be eight characters or longer
The password must contain at least 2 lowercase alphabetical character.
The password must contain at least 2 uppercase alphabetical character.
The password must contain at least 2 numeric character.
The password must contain at least 2 special character.
My code
function checkPass(pw) {
var regx = new RegExp("^(?=.*[a-z]{2})(?=.*[A-Z]{2})(?=.*[0-9]{2})(?=.*[!##\$%\^&\*\)\(]{2})(?=.{8,})");
return regx.test(pw);
}
checkPass('PAssword12#$') => true
checkPass('PaSsword12#$') => false
I want to funtion return true when 2 uppercase character is not sequential.
Thanks!
You need to use the $ anchor to check for length (and best is to move that check out from lookaheads) and to allow some non-uppercase letters in between like this:
function checkPass(pw) {
var regx = /^(?=(?:[^a-z]*[a-z]){2})(?=(?:[^A-Z]*[A-Z]){2})(?=(?:\D*\d){2})(?=(?:[^!##$%^&*)(]*[!##$%^&*)(]){2}).{8,}$/;
return regx.test(pw);
}
document.write(checkPass('PAssword12#$') + "<br>");
document.write(checkPass('PaSsword12#$'));
Note that I used the principle of contrast: (?:[^a-z]*[a-z]){2} matches 2 sequences of symbols other than a-z zero or more times followed by 1 lowercase letter. I modified all the lookaheads the same way.
Rather than having [A-Z]{2} which will only match two uppercase characters together, you'll have to put in an optional match for any other characters in between two separate ranges (you'll have to do this for the lowercase, numbers and symbols as well). So you would instead put
[A-Z].*?[A-Z]
You also don't actually need to check whether it's at least 8 characters, because any password meeting the criteria for lowercase/uppercase letters, numbers and symbols has to be 8 characters at minimum anyway.

JavaScript Regular Expression Validation

I'm attempting to validate a field name to match a certain format in JavaScript using Regular Expressions.
I need the string inputted to resemble this:
word\word\word
So anything inputted can't be blank, and it must be three words seperated by a backslash.
This is the code i'm working with, but i'm not sure if the pattern is the right syntax?!!
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/[a-Z|/\\/|a-Z|/\\/|a-Z\s]/;
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
}
else
{
alert("match");
}
}
Any help will be very appreciated!!!
If by word you mean the English letters a-z in upper or lower case, then:
/^(?:[a-z]+\\){2}[a-z]+$/i
That says:
^ Beginning of string
(?:...) Non-capturing group
[a-z]+ One or more letters a-z (or A-Z because of the i flag at the end). If you also want to allow some other characters, just add them to the [a-z] after the z. If you want to allow hyphens, add \- to it (you need the backslash, depending on where you put the hyphen, so I just always include it). Note that this is very English-centric, and even in English sometimes people write borrowed words with their non-English letters, such as résumé.
\\ Backslash
{2} Repeated twice
(Then another word)
$ End of string
The issues with your expression are:
[a-Z] Is invalid because the range is out of order (Z comes before a). If it were valid (or if you wrote [Z-a]), it would matches everything between Z and a, which isn't just a-z and A-Z
\\/ Requires a backslash and then a slash
| is an alternation (this or that)
\s is whitespace
Try /^[a-z]+\\[a-z]+\\[a-z]+$/
function validateResourceName() {
//get posted resource name value
var inputString = document.getElementById("resourceName").value;
//should be in the word\word\word format
var pattern=/^[a-z]+\\[a-z]+\\[a-z]+$/
//If the inputString is NOT a match
if (!pattern.test(inputString)) {
alert("not a match");
} else {
alert("match");
}
}
If you want to allow the word matching to be case insensitive;
`/^[a-z]+\\[a-z]+\\[a-z]+$/i`
If you want to be a bit more broad with what you define as a 'word', and allow it to consist of alphanumeric characters and underscore;
`/^\w+\\\w+\\\w+$/i`
you can just use this \w+\\\w+\\\w+
or
[a-zA-Z]+(\\[a-zA-Z]+){2}
This should do it
^\w+\\\w+\\\w+$
In javascript
if (/^\w+\\\w+\\\w+$/.test(subject)) {
// Successful match
} else {
// Match attempt failed
}
Try this one , See the Regex fiddle for regex demo and Jsfiddle for the code demo
Regex
/(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g
Javascript
function validateResourceName(string) {
var pattern = /(\w)*\\(?!\\)(\w)*\\(?!\\)(\w)*(?!\\)/g;
if (!pattern.test(string)) {
alert("not a match");
} else {
alert("match");
}
}

Categories