I want to restrict the user to enter in textbox only string followed by number only for e.g
AA1->true
AA1A->False
AA12->True
AB12AA14AB->false
12AA->false
ABC12->false
AA->false
So please let me know how can I add validation for above condition/cases using javascript.
Use a regular expression:
const validate = str => /^[A-Z]+\d+$/.test(str);
`AA1
AA1A
AA12
AB12AA14AB
12AA
ABC12
AA`
.split('\n')
.forEach(str => console.log(validate(str)));
^ indicates the start of the string, [A-Z]+ matches one or more uppercase alphabetical characters, \d+ matches one or more numbers, and $ matches the end of the string.
function isStrEndWithNum(str){
if(str)
return !isNaN(str[str.length-1]);
return false;
}
You can use the .test function which is present in JavaScript
/^([\w]+[0-9])$/.test('YourStringHere');
i am just confused with second last condition of yours.
Other than that all your conditions are passed with the above code.
Related
I'm creating a form for getting information about the user in html and javascript and I am struggling to check if one of my text box inputs is in a specific format.
The format is: ### ###
Where each # is either a letter or a number, an example of this would be N3H 2E9.
My input is from a regular html text box that is being converted into a const within my javascript and I'm wondering if there is a way to validate that the input is in the same format as previously mentioned. I'm pretty new to html and javascript so if you answer please could you provide a small explanation behind your answer?
You can use Regular Expressions (RegEx) to do what you want.
const correctInput = "N3H 2E9";
const incorrectInput = "N3H 2Ea";
const isValid = (input) => /^[0-9A-Z]{3} [0-9A-Z]{3}$/.test(input);
console.log(isValid(correctInput));
console.log(isValid(incorrectInput));
/^[0-9A-Z]{3} [0-9A-Z]{3}$/
^: Matches start of the string
[0-9A-Z]{3}: Matches exactly three characters which are one of uppercase A-Z or digits 0-9
: Matches space
$: Matches end of the string
function validateForm() {
var postalCode = document.getElementById("postal_code").value;
// This solution uses a regular expression to test the input for our desired format
// for more info on what this pattern means exactly, check out
// https://regex101.com/?regex=^[A-Z0-9]{3}%20[A-Z0-9]{3}$
var rgx = /^[A-Z0-9]{3} [A-Z0-9]{3}$/;
var isValid = rgx.test(postalCode);
var resultElement = document.getElementById("result");
if (isValid) {
resultElement.innerText = "Valid"
} else {
resultElement.innerText = "Invalid"
}
}
<input type="text" id="postal_code">
<button onclick="validateForm()">Validate</button>
<span id="result">Invalid</span>
This is most easily accomplished using a regular expression.
A regular expression defines a pattern of characters that input can be tested against. In javascript you can create one as follows:
const expression = /test/
expression is now a regular expression and you can use it to validate strings (in this case, testing whether a part of it contains "test"):
expression.test("Hello") // false
expression.test("test") // true
expression.test("Hello this is a test") // true
expression.test("Hey I'm testing") // true
expression.test("t est") // false
expression.test("Test") // false
Regular expressions can contain special selectors that define not a literal string ("test" for example) but a range of allowed characters. In your example you want to test against numbers and capital letters. That can be notated as [A-Z0-9] meaning "any character between A and Z or between 0 and 9". You want three of those, which can be notated as [A-Z0-9][A-Z0-9][A-Z0-9] or simply as [A-Z0-9]{3}. The final expression would look like:
const expression = /^[A-Z0-9]{3} [A-Z0-9]{3}$/
Note the special characters ^ and $. They correspond with the beginning and ending of a string, ensuring you're not matching any string merely containing a postal code, but only strings exclusively containing a postal code.
Finally, you could write this function as follows:
const isCanadianPostalCode = input => /^[A-Z0-9]{3} [A-Z0-9]{3}$/.test(input);
console.log( isCanadianPostalCode('N3H 2E9A') ) // false
console.log( isCanadianPostalCode('N3H 2E9') ) // true
I'm trying to build a regex which allows the following characters:
A-Z
a-z
1234567890
!##$%&*()_-+={[}]|\:;"'<,>.?/~`
All other characters are invalid. This is the regex I built, but it is not working as I expect it to. I expect the .test() to return false when an invalid character is present:
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*/g
return regex.test(string);
}
In this case, the test is always returning "true", even when "^" is present in the string.
Your regex only checks that at least one of the allowed characters is present. Add start and end anchors to your regex - /^...$/
var string = 'abcd^wyd';
function isValidPassword () {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g
return regex.test(string);
}
... another approach, is instead of checking all characters are good, to look for a bad character, which is more efficient as you can stop looking as soon as you find one...
// return true if string does not (`!`) match a character that is not (`^`) in the set...
return !/[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/.test()
Instead of searching allowed characters search forbidden ones.
var string = 'abcd^wyd';
function regTest (string) {//[^ == not
var regex = /[^0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]/g
return !regex.test(string);//false if found
}
console.log(regTest(string));
The regex, as you've written is checking for the existence of the characters in the input string, regardless of where it appears.
Instead you need to anchor your regex so that it checks the entire string.
By adding ^ and $, you are instructing your regex to match only the allowed characters for the entire string, rather than any subsection.
function isValidPassword (pwd) {
var regex = /^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]*$/g\;
return regex.test(pwd);
}
alert(isValidPassword('abcd^wyd'));
Your regexp is matching the first part of o=your string i.e. "abcd" so it is true . You need to anchor it to the start (using ^ at the beginning) and the end of the string (using $ at the end) so your regexp should look like:
^[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]+[0-9A-Za-z!##$%&*()_\-+={[}\]|\:;"'<,>.?\/\\~`]$
That way it will need to match the entire string.
You can visualize it in the following link:
regexper_diagram
This regex will work.
var str = 'eefdooasdc23432423!##$%&*()_-+={[}]|:;"\'<,>.?/~\`';
var reg = /.|\d|!|#|#|\$|%|&|\*|\(|\)|_|-|\+|=|{|\[|}|]|\||:|;|"|'|<|,|>|\.|\?|\/|~|`/gi;
// test it.
reg.test(str); //true
I use this site to test my regex.
Regex 101
I know there are several question like this on Stack-overflow, but I can't seem to get a straight answer out of the questions already posted.Looking forward if someone can help me.
I want to validate a string & return TRUE if it satisfies below condition
String contains only one special character i.e _ (underscore)
& this special character should not appear at beginning or end of the string
Example:
var demo1="23dsfXXXa32_XXXX" // Valid, should returns TRUE
var demo2="_23dsfXXXa32_XXXX" // Invalid,should returns FALSE
var demo3= "23dsfXXXa32XXXX_" //invalid,should returns FALSE
var demo4= "_" //invalid,should returns FALSE
var demo5= "&sdfsa_XX";// returns false
Tried: FIDDLE
if(/^[a-zA-Z0-9_ ]*$/.test(demo1) == true) {
alert('Valid String');
}
Result: Not functioning as per expected
Since you've said you require that the character be there, one way is to do it with a regular expression is with a negated character class at each end with a non-negated one in the middle:
var rex = /^[^_]+[_][^_]+$/;
That only handle underscores; add other "special" characters to all three character classes there.
How that works:
^ matches start of string
[^_]+ requires one or more characters not in the class
[_] requires exactly one character in the class
[^_]+ requires one or more characters not in the class
$ matches end of string
You could simplify it by using indexOf to verify that its not in the first or last position and split to see if its there only once. This is usually faster than a regex pattern.
function checkString(str){
return str.indexOf("_") !== 0 && str.indexOf("_") !== str.length-1 && str.split("_") === 2;
}
I am trying to validate a string, that should contain letters numbers and special characters &-._ only. For that I tried with a regular expression.
var pattern = /[a-zA-Z0-9&_\.-]/
var qry = 'abc&*';
if(qry.match(pattern)) {
alert('valid');
}
else{
alert('invalid');
}
While using the above code, the string abc&* is valid. But my requirement is to show this invalid. ie Whenever a character other than a letter, a number or special characters &-._ comes, the string should evaluate as invalid. How can I do that with a regex?
Add them to the allowed characters, but you'll need to escape some of them, such as -]/\
var pattern = /^[a-zA-Z0-9!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/
That way you can remove any individual character you want to disallow.
Also, you want to include the start and end of string placemarkers ^ and $
Update:
As elclanrs understood (and the rest of us didn't, initially), the only special characters needing to be allowed in the pattern are &-._
/^[\w&.\-]+$/
[\w] is the same as [a-zA-Z0-9_]
Though the dash doesn't need escaping when it's at the start or end of the list, I prefer to do it in case other characters are added. Additionally, the + means you need at least one of the listed characters. If zero is ok (ie an empty value), then replace it with a * instead:
/^[\w&.\-]*$/
Well, why not just add them to your existing character class?
var pattern = /[a-zA-Z0-9&._-]/
If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:
var pattern = /^[a-zA-Z0-9&._-]+$/
The added ^ and $ match the beginning and end of the string respectively.
Testing for letters, numbers or underscore can be done with \w which shortens your expression:
var pattern = /^[\w&.-]+$/
As mentioned in the comment from Nathan, if you're not using the results from .match() (it returns an array with what has been matched), it's better to use RegExp.test() which returns a simple boolean:
if (pattern.test(qry)) {
// qry is non-empty and only contains letters, numbers or special characters.
}
Update 2
In case I have misread the question, the below will check if all three separate conditions are met.
if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
// qry contains at least one letter, one number and one special character
}
Try this regex:
/^[\w&.-]+$/
Also you can use test.
if ( pattern.test( qry ) ) {
// valid
}
let pattern = /^(?=.*[0-9])(?=.*[!##$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!##$%^&*]{6,16}$/;
//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format
let reee =pattern .test("helLo123#"); //true as it contains all the above
I tried a bunch of these but none of them worked for all of my tests. So I found this:
^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$
from this source: https://www.w3resource.com/javascript/form/password-validation.php
Try this RegEx: Matching special charecters which we use in paragraphs and alphabets
Javascript : /^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$/.test(str)
.test(str) returns boolean value if matched true and not matched false
c# : ^[a-zA-Z]+(([\'\,\.\-_ \/)(:][a-zA-Z_ ])?[a-zA-Z_ .]*)*$
Here you can match with special char:
function containsSpecialChars(str) {
const specialChars = /[`!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
return specialChars.test(str);
}
console.log(containsSpecialChars('hello!')); // 👉️ true
console.log(containsSpecialChars('abc')); // 👉️ false
console.log(containsSpecialChars('one two')); // 👉️ false
How can I write a regex that match this
123/456
123/456/?
but not this
123/456/
I want on the second / it must be followed by a ?.
For Example I would like it to match this
'123/456'.match(X) // return ['123/456']
'123/456/?'.match(X) // return ['123/456/?']
'123/456/'.match(X) // return null
Update
I missed to say one important thing. It must not end with '?', a string like '123/456/?hi' should also match
You can try this regex: \d{3}/\d{3}(/\?.*)?
It will match
3 digits
followed by a /
followed by 3 digits
followed by /?any_text (e.g. /?hi) (optional)
This example uses regular expression anchors like ^ and $, but they are not required if you only try to match against the target string.
var result = '123/456/?hi'.match(/\d{3}\/\d{3}(\/\?.*)?/);
if (result) {
document.write(result[0]);
}
else {
document.write('no match');
}
This regular expression will work /^\d{3}\/\d{3}(\/\?.*)?/
See this JSFiddle.
Note: if you think it should match any number of digits then use \d+ instead of \d{3}. The later matches exactly 3 digits.
Here you are:
[0-9]+/[0-9]+(/\?[^ ]*)?
What other rules do you have?
If you want to accept all strings with last character other than ?, use "[^?]$"
If you want to accept strings that start with 123/456 and optionally end with /?, use "^123/456(/\?)?$"
I think this should work:
'123/456'.match(/^123\/456(\/\?)?$/) // returns ["123/456", undefined]
'123/456/'.match(/^123\/456(\/\?)?$/) // returns null
'123/456/?'.match(/^123\/456(\/\?)?$/) // returns ["123/456/?", "/?"]
EDIT: added the other cases