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>
Related
The input I want the user to key in is in either of these formats:
D345/98765/2030
D345s/98765/2030
Let me try to explain it. It should start with:
one letter (uppercase or lowercase)
followed by a maximum of 3 numbers
then another OPTIONAL single letter which can be either uppercase or lowercase
then a forward slash followed by a maximum of five numbers
then another forward slash followed by exactly 4 numbers.
Just to mention, spaces are not allowed. I'm new to this validation and any assistance would be highly appreciated. I've checked existing questions and none answers this satisfactorily. Kindly assist me with the JavaScript code, Here is my input code:
<div class='control-group'>
<!-- Reference-->
<div class='controls'>
<input required type='text' autocomplete='off' id='reference' name='reference' placeholder='Enter your reference number'>
</div>
</div>
Maybe this regex is what you are looking for:
^[a-zA-Z]\d{1,3}[a-zA-Z]?\/\d{1,5}\/\d{4}$
From the beginning of the string ^
One letter(case insensitive) [a-zA-Z]
Up to 3 numbers \d{1,3}
Optional single letter (case insensitive) [a-zA-Z]?
Forward slash \/
Up to five numbers \d{1,5}
Forward slash \/
Exactly 4 numbers \d{4
to the end of the string $
Edit: based on your question about the "Invalid reference number" alert
You could implement your code like this:
function ValidateInput() {
var textBoxvalue = document.getElementById('reference').value;
var pattern = /^[a-zA-Z]\d{1,3}[a-zA-Z]?\/\d{1,5}\/\d{4}$/;
if (pattern.test(textBoxvalue)) {
alert('Good to go');
}
else {
alert('Invalid reference number');
}
}
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*$/))
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.
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;
}
The following JavaScript code returns false if the string contains only numbers or characters other than [a-zA-Z0-9_].
function validate(n) {
return (!/^[\d]+$/.test(n) && /^[\w]+$/.test(n));
}
Is it possible to do this with just a regexp? I want to take advantage of pattern attributes on the input tag for validation.
<input type="text" pattern="...">
Edit: I also want it to be between 5 and 20 characters
Like this: ^[a-zA-Z0-9_]*[a-zA-Z_]+[a-zA-Z0-9_]*$
This regex matches zero or more characters including numbers, at least one character that isn't a number, followed by another zero or more characters including numbers.