javaScript check for at least one alphanumeric character in string - javascript

In my application someone can submit text from another language. I'd like for only English alphanumeric strings to be entered. I've got this JavaScript function working but wondering if this is the best method for doing this?
var string = $('input[name=title]').val();
if((/\d/.test(string) || /[a-zA-Z]/.test(string)) === false) {
alert('Field has no Alphanumeric characters.');
fPass = false;
}
Even if some just enters 1 character I want that to be allowed, as long as it is a number or a character from one of the 26 letters in the English alphabet (case insensitive)
Without using a function here is what I've come up with
if((/[\da-z]/i.test(string)) === false) {
alert('Please use alphanumeric characters.')
}

You can combine your regex into one expression.
function hasAlphanumeric(str) {
return /\d|[A-z]/.test(str)
}

You can use
^[\da-z]+$
let allowAlphanumeric = (str) =>{
return /^[\da-z]+$/i.test(str)
}
console.log(allowAlphanumeric('$##'))
console.log(allowAlphanumeric(''))
console.log(allowAlphanumeric(' '))
console.log(allowAlphanumeric('abchbchdb12e44'))

Related

checking if a string follows a given pattern in javascript

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}$">

hyphens in Regular Expressions/ javascript camelCase function

The Function should take a string as an argument and camel case it. I am having trouble with hyphens while using regex and string.replace() method.
camelCase('state-of-the-art') should return 'state-of-the-art'
camelCase("Don't worry kyoko") should return "dontWorryKyoko"
The following works for both cases, but I want to make it DRY, take out the hyphens if clause and include the hyphen case in .replace() and it's call-back.
function camelCase(phrase) {
let re = /[a-z]+/i;
let hyphens = /[-+]/g
if(typeof phrase !== 'string' || !phrase.match(re) || !phrase || phrase === null){
return "Please enter a valid string.";
} else if (phrase.match(hyphens)){
return phrase.toLocaleLowerCase();
}else{
return phrase.replace(/(?:^\w+|[A-Z]|\s+\w)/g, function(letter, index) {
return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\W+/g, '');
}
}
console.log(camelCase('state-of-the-art')) // 'state-of-the-art'
console.log(camelCase("Don't look back")) // dontLookBack
Can we make the hyphen case work without the hyphens if clause?
Also I feel like camelCase("don't lOOk_BaCK") should lowercase letters with index > 0 but it doesn't seem to be doing that in the console.
Anyone wanna help with this? Thanx
To cope with the hyphen issue you may consider - a part of alphanumeric class by using [\w-] or [^\w-] where appropriate.
To lowercase all non-first letters I suggest to match all words with (\S)(\S*) uppercasing $1 (where appropriate) and lowercasing $2:
function camelCase(phrase) {
return phrase.replace(/[^\w-]*(\S)(\S+)/g, function(_, first, rest, index) {
return (index ? first.toUpperCase() : first.toLowerCase())
+ rest.toLowerCase();
}).replace(/[^\w-]+/g, "");
}
console.log(camelCase("state-of-the-art"));
console.log(camelCase("-state-of-the-art"));
console.log(camelCase("Don't look back"));
console.log(camelCase("don't lOOk_BaCK"));
console.log(camelCase("???don't lOOk_BaCK"));
You can make the hyphens work by adding a negative lookahead assertion .replace(/(?!-)\W+/g, '');. This would tell it to replace all non-word characters, except a - dash character.
Regarding your lower-casing problem: your only criteria right now to decide the case is if it appears at the beginning of the string. Otherwise you're UPPER casing everything (including the upper case matches). This is also a pretty easy fix. Here's the whole thing:
function camelCase(phrase) {
let re = /[a-z]+/i;
if (typeof phrase !== 'string' || !phrase.match(re) || !phrase || phrase === null) {
return "Please enter a valid string.";
} else {
return phrase.replace(/(?:^\w+|(\s+)\w)|[A-Z]/g, function (letter, sp, index) {
console.log(letter, sp, index);
return (index == 0 || sp === undefined) ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/(?!-)\W+/g, '');
}
}
Explanation of the changes:
change order of asssertions in phrase.replace regexp. We want a space-word combo to take precedence over a capitalized match.
add a capturing group to the space, so that we can know better if the capture follows a space
change the boolean expression: we want it to be lower case if:
it's the first character (index===0)
OR there isn't a space match (this would be an [A-Z] match, without a preceding space)
Also just as an aside, you don't appear to be camel-casing on a _ underscore character, only on spaces. Is this intentional? I've never seen a camel-case routine that didn't convert snake-case (underscore).

javascript validation for special character's index/position

I have input as 23 digit key from input box which will be separated by '-'.
E.g: XXXXX-XXXXX-XXXXX-XXXXX
This is expected format means, 5 digit followed by -(hyphen).
Problem:
User can input any data/wrong format, like XXX-XXXXX-XXXXX-XXXXXXX, in this case index of hyphen is invalid. How can I valided the index of hyphen?
I tried:
if((prd_len==23) && (n!=-1))
{
var indices = [];
for(var i=0; i<prd_id.length;i++)
{
if (prd_id[i] === "-")
{
indices.push(i);
}
}
for(var x=0;x<indices.length;x++)
{
if((indices[x]!=5) || (indices[x]!=11) || (indices[x]!=17))
{
$('#msgErr1').text('Please enter valid key.');
flag=1;
}
}
}
where prd_len=length of the accepted input from user.
Try regular expressions
if(input.match(/^(\d{5}-){3}\d{5}$/))
everything is OK
This expression basically reads "five digits and a dash - three times, then five digits". For further reference see
http://www.regular-expressions.info/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
As thg435 said, but more human-readable :-)
var correct = input.match(/^\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d-\d\d\d\d\d$)

JS: regex for numbers and spaces?

I'm using happyJS and use the regex underneath for phone validation
phone: function (val) {
return /^(?:[0-9]+$)/.test(val);
}
However this ONLY allows numbers. I want the user to be able to enter spaces as well like
238 238 45383
Any idea why return /^(?:[0-9 ]+$)/.test(val); is not doing the trick?
This is my suggested solution:
/^(?=.*\d)[\d ]+$/.test(val)
The (?=.*\d) asserts that there is at least one digit in the input. Otherwise, an input with only blank spaces can match.
Note that this doesn't put any constraint on the number of digits (only makes sure there are at least 1 digit), or where the space should appear in the input.
Try
phone: function (val) {
return /^(\s*[0-9]+\s*)+$/.test(val);
}
At least one number must be present for the above to succeed but please have a look at the
regex example here
Try
/^[\d ]*$/.test("238 238 45383")
console.log(/^[\d ]*$/.test("238 238 45383"));
You can try the below regex for checking numbers and spaces.
function isTextAndNumberSpaceOnly(text) {
var regex = /^[0-9 ]+$/;
if (regex.test(text)) {
return true;
} else {
return false;
}
}
Personally I use this code and it works properly:
function validateMobile(mob)
{
var re = /^09[0-9]{9}$/
if(mob.match(re))
return true;
else
return false;
}

alphanumeric regex javascript

I am having a problem to get the simple reges for alphanumeric chars only work in javascript :
var validateCustomArea = function () {
cString = customArea.val();
var patt=/[0-9a-zA-Z]/;
if(patt.test(cString)){
console.log("valid");
}else{
console.log("invalid");
}
}
I am checking the text field value after keyup events from jquery but the results are not expected, I only want alphanumeric charachters to be in the string
This regex:
/[0-9a-zA-Z]/
will match any string that contains at least one alphanumeric character. I think you're looking for this:
/^[0-9a-zA-Z]+$/
/^[0-9a-zA-Z]*$/ /* If you want to allow "empty" through */
Or possibly this:
var string = $.trim(customArea.val());
var patt = /[^0-9a-z]/i;
if(patt.test(string))
console.log('invalid');
else
console.log('valid');
Your function only checks one character (/[0-9a-zA-Z]/ means one character within any of the ranges 0-9, a-z, or A-Z), but reads in the whole input field text. You would need to either loop this or check all characters in the string by saying something like /^[0-9a-zA-Z]*$/. I suggest the latter.
I fixed it this way
var validateCustomArea = function () {
cString = customArea.val();
console.log(cString)
var patt=/[^0-9a-zA-Z]/
if(!cString.match(patt)){
console.log("valid");
}else{
console.log("invalid");
}
}
I needed to negate the regex

Categories