I'm trying to check if a string contains certain characters. I was going to use regex, but my string may not have a format.
I would like to ensure that i'm allowing only the following characters
1. + symbol
2. - symbol
3. numbers 0~9
4. (
5. )
6. . (dot)
7. spaces
This regex will match a string containing only those characters:
^[+\-0-9(). ]+$
Working Demo
if ( string.match('[^(). +\-0-9]') ) {
alert("Invalid string");
}
Try this:
var isValid = /^[\x2B\x2D\x28\x29\x2E\s\d]+$/.test(input);
if(isValid ) {
//...
} else {
//..invalid
}
Related
I am still new to javascript and I am trying to validate my form.
One of my inputs is a text input for an identity number that follows the following pattern: ####XX where # represents a number and X represents a capital letter from A-Z.
Here is my code so far:
var IDnum = document.getElementById('identityNumber').value;
if ( (isNaN(IDnum.charAt(0))) && (isNaN(IDnum.charAt(1)))&& (isNaN(IDnum.charAt(2))) && (isNaN(IDnum.charAt(3))) && (!isNaN(IDnum.charAt(4))) )
{
document.getElementById('identityError').style.display = "inline-block";
}
else
{
document.getElementById('identityError').style.display = "none";
}
I have tried to google it and have seen some info where they use a RegExp however i have yet to learn anything like that.
With my code above, no matter what i type it, it still validates it. Any ideas what i am doing wrong and if there is a more simple and easier way?
EDIT: after looking to regex and similar answers the following
^\d{4}[A-Z]{2}$
did not work either
A regular expression is the way to go here. Use the pattern ^\d{4}[A-Z]$:
document.querySelector('button').addEventListener('click', (e) => {
const { value } = document.querySelector('input');
if (value.match(/^\d{4}[A-Z]$/)) {
console.log('OK');
} else {
console.log('Bad');
}
});
<input>
<button>submit</button>
^\d{4}[A-Z]$ means:
^ - Match the start of the string
\d{4} - Match a digit character (0 to 9) 4 times
[A-Z] - Match a character from A to Z
$ - Match the end of the string
You can use regular expression to identify whether string has 4 digits before a character.
each \d represents a digit, \d\d\d\d means 4 digits (alternatively \d{4}).
followed by . means 4 digits followed by any character.
function isAllowed(str) {
return str.match(/^\d\d\d\d.$/g) !== null
}
console.log(isAllowed("1234X"));
console.log(isAllowed("123a"));
console.log(isAllowed("3892#"));
console.log(isAllowed("X"));
var IDnum = document.getElementById('identityNumber').value;
if (isAllowed(IDnum))
{
document.getElementById('identityError').style.display = "inline-block";
}
else
{
document.getElementById('identityError').style.display = "none";
}
function RegexCheck(str) {
var pettern = new RegExp('^[0-9]{4,}[A-Z]{1,}');
return pettern.test(str);
}
console.log(RegexCheck("####X"));
console.log(RegexCheck("1234A"));
console.log(RegexCheck("2C35B"));
console.log(RegexCheck("A698C"));
console.log(RegexCheck("1698b"));
You can use the pattern attribute to provide a RegExp string:
^\d{4}[A-Z]{2}$ would be a string consisting of 4 digits followed by two capital letters between A and Z.
Explanation
^: Beginning of the string.
\d{4}: Exactly 4 digits in a row (this could also be written as \d\d\d\d)
[A-Z]{2}: Exactly 2 characters from the range of character between A and Z (alternatively [A-Z][A-Z]).
$: The end of the string.
input:invalid {
color: red;
}
input:not(:invalid) {
color: green;
}
<input type="text" pattern="^\d{4}[A-Z]{2}$">
I am trying to make a HTML form that accepts a rating through an input field from the user. The rating is to be a number from 0-10, and I want it to allow up to two decimal places. I am trying to use regular expression, with the following
function isRatingGood()
{
var rating = document.getElementById("rating").value;
var ratingpattern = new RegExp("^[0-9](\.[0-9][0-9]?)?$");
if(ratingpattern.test(rating))
{
alert("Rating Successfully Inputted");
return true;
}
else
{
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
However, when I enter any 4 or 3 digit number into the field, it still works. It outputs the alert, so I know it is the regular expression that is failing. 5 digit numbers do not work. I used this previous answer as a basis, but it is not working properly for me.
My current understanding is that the beginning of the expression should be a digit, then optionally, a decimal place followed by 1 or 2 digits should be accepted.
You are using a string literal to created the regex. Inside a string literal, \ is the escape character. The string literal
"^[0-9](\.[0-9][0-9]?)?$"
produces the value (and regex):
^[0-9](.[0-9][0-9]?)?$
(you can verify that by entering the string literal in your browser's console)
\. is not valid escape sequence in a string literal, hence the backslash is ignored. Here is similar example:
> "foo\:bar"
"foo:bar"
So you can see above, the . is not escaped in the regex, hence it keeps its special meaning and matches any character. Either escape the backslash in the string literal to create a literal \:
> "^[0-9](\\.[0-9][0-9]?)?$"
"^[0-9](\.[0-9][0-9]?)?$"
or use a regex literal:
/^[0-9](\.[0-9][0-9]?)?$/
The regular expression you're using will parsed to
/^[0-9](.[0-9][0-9]?)?$/
Here . will match any character except newline.
To make it match the . literal, you need to add an extra \ for escaping the \.
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
Or, you can simply use
var ratingPattern = /^[0-9](\.[0-9][0-9]?)?$/;
You can also use \d instead of the class [0-9].
var ratingPattern = /^\d(\.\d{1,2})?$/;
Demo
var ratingpattern = new RegExp("^[0-9](\\.[0-9][0-9]?)?$");
function isRatingGood() {
var rating = document.getElementById("rating").value;
if (ratingpattern.test(rating)) {
alert("Rating Successfully Inputted");
return true;
} else {
return rating === "10" || rating === "10.0" || rating === "10.00";
}
}
<input type="text" id="rating" />
<button onclick="isRatingGood()">Check</button>
Below find a regex candidate for your task:
^[0-1]?\d(\.\d{0,2})?$
Demo with explanation
var list = ['03.003', '05.05', '9.01', '10', '10.05', '100', '1', '2.', '2.12'];
var regex = /^[0-1]?\d(\.\d{0,2})?$/;
for (var index in list) {
var str = list[index];
var match = regex.test(str);
console.log(str + ' : ' + match);
}
This should also do the job. You don't need to escape dots from inside the square brackets:
^((10|\d{1})|\d{1}[.]\d{1,2})$
Also if you want have max rating 10 use
10| ---- accept 10
\d{1})| ---- accept whole numbers from 0-9 replace \d with [1-9]{1} if don't want 0 in this
\d{1}[.]\d{1,2} ---- accept number with two or one numbers after the coma from 0 to 9
LIVE DEMO: https://regex101.com/r/hY5tG4/7
Any character except ^-]\ All characters except the listed special characters are literal characters that add themselves to the character class. [abc] matches a, b or c literal characters
Just answered this myself.
Need to add square brackets to the decimal point, so the regular expression looks like
var ratingpattern = new RegExp("^[0-9]([\.][0-9][0-9]?)?$");
Is it possible to check whether a string contains only special characters using javascript?
Match where the string has only characters, that are not in the class defined here as a-z, A-Z or 0-9.
var regex = /^[^a-zA-Z0-9]+$/
Test it...
console.log( "My string to test".match(regex) )
console.log( "My string, to test!".match(regex) )
Yes it is possible. Try below, it should work.
function hasOnlySpecialCharater(val) {
var pattern = /^[^a-zA-Z0-9]+$/;
return (pattern.test(val));
}
console.log(hasOnlySpecialCharater("##$"));
console.log(hasOnlySpecialCharater("ChiragP&^"));
We can write this :
function checkOnlySplChar(str) {
// to check if string contains only special characters
var alphaNumOnly = RegExp('/^[^a-zA-Z0-9]+$/');
return (alphaNumOnly.test(str));
}
I want to validate a text field (first name) using javascript. such that it should only contain text. NO special characters and No numbers.and since it is just the first name it should only contain one word. (no spaces)
Allowed:
John
john
Not Allowed
john kennedy.
John kennedy.
john123.
123john.
I tried this but its not working.
if( !validateName($fname))
{
alert("name invalid");
}
function validateName($name) {
var nameReg = /^A-Za-z*/;
if( !nameReg.test( $name ) ) {
return false;
} else {
return true;
}
}
EDIT:
I tried
var nameReg = /^[A-Za-z]*/;
but it still doesn't show the alert box when I enter john123 or 123john.
nameReg needs to be /^[a-z]+$/i (or some varient). The ^ matches the start of the string and $ matches the end. This is "one or more a-z characters from the start to the end of the string, case-insensitive." You can change + to *, but then the string could be empty.
http://jsfiddle.net/ExplosionPIlls/pwYV3/1/
Use a character class:
var nameReg = /^[A-Za-z]*/;
Without the containing [] (making it a character class), you're specifying a literal A-Za-z.
UPDATE:
Add a $ to the end of the Regex.
var nameReg = /^[A-Za-z]*$/;
Otherwise, john123 returns valid as the Regex is matching john and can ignore the 123 portion of the string.
Working demo: http://jsfiddle.net/GNVck/
i need a javascript function that able to check for digit and - only.
example: 1,2,3,4,5,6,7,8,9,0 will return true
and - will return true as well.
other than that all return false including enter is pressed.
i have a function like this:
function IsNumeric(sText){
var filter = /^[0-9-+]+$/;
if (filter.test(sText)) {
return true;
}else {
return false;
}
}
i call it like this:
if(!IsNumeric(value)) {
alert("Number and - only please");
}
for some reason it does not work, any method to do the verification without using regex?
EDIT: OK, updated as per your comment, an expression to match either a lone minus sign or any combination of digits with no minus sign:
function IsNumeric(sText){
return /^(-|\d+)$/.test(sText);
}
If you want only positive numbers and don't want to allow leading zeros then use this regex:
/^(-|[1-9]\d*)$/
Regarding your question "any method to do the verification without using regex?", yes, there are endless ways to achieve this with the various string and number manipulation functions provided by JS. But a regex is simplest.
Your function returns true if the supplied value contains any combination of digits and the plus or minus symbols, including repeats such as in "---+++123". Note that the + towards the end of your regex means to match the preceding character 1 or more times.
What you probably want is a regex that allows a single plus or minus symbol at the beginning, followed by any combination of digits:
function IsNumeric(sText){
return /^[-+]?\d+$/.test(sText);
}
? means match the preceding character 0 or 1 times. You can simplify [0-9] as \d. Note that you don't need the if statement: just return the result from .test() directly.
That will accept "-123", "123", "+123" but not "--123". If you don't want to allow a plus sign at the beginning change the regex to /^-?\d+$/.
"example: 1,2,3,4,5,6,7,8,9,0 will return true and - will return true as well."
Your example seems to be saying that only a single digit or a single minus sign is considered valid - if so then try this:
function IsNumeric(sText){
return /^[\d-]$/.test(sText);
}
How about
function IsNumeric(s) {
return /^(+|-|)\d*$/.test(s);
}
Hiphen(-) has special meaning so use escape character in character set.
Try this:
var filter = /^[0-9\-]+$/;
Can be simple ... try this:
function IsNumeric(str) {
return str.length == 1 && (parseInt(str) < 10 || str == "-");
}