How to check if string contains character at any point in javascript - javascript

I need to know if a string contains a character (one or multiple times) at any point of the string.
For example with the character "&":
"&hfds" is invalid, "%$/&h&" is invalid etc.
Im doing this as part of a password validation:
function applySpecialCharacterFilter(password) {
if (password.match(/([!,%,#,#,$,^,*,?,_,~])/)) {
return 1;
} else if(password.match(/([&])/)) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
in the first part it checks of the password contains any of the allowed characters, and then increments the value of the validation. But then passwords containing not allowed characters can pass.
With the else if im trying to catch it, but it only works if its not in a special character sequence like $%&
Thank you
Edit:
Here is the whole function:
function checkStrength(password){
var strength = 0;
var passwordMessage = $('#passwordMessage');
if (password.length == 0) {
result.removeClass();
return '';
}
if (password.length < 6) {
validPassword = false;
result.removeClass();
result.addClass('short');
return 'Too short';
} else if(password.length > 8) {
validPassword = false;
result.removeClass();
result.addClass('short');
return 'Too long';
} else {
strength += 1;
}
try {
strength += applyLowerAndUpperCaseFilter(password);
strength += applyNumbersAndCharactersFilter(password);
strength += applySpecialCharacterFilter(password);
strength += applyTwoSpecialCharacterFilter(password);
strength += applyAlphabeticalCharacterCriteria(password);
} catch(error) {
validPassword = false;
result.removeClass();
result.addClass('short');
passwordMessage.html('').append('<p>TPassword contains invalid characters!</p>');
return 'Invalid';
}
passwordMessage.html('');
if (strength <= 2) {
validPassword = false;
result.removeClass();
result.addClass('weak');
return 'Schwach';
} else if (strength <= 3 ) {
validPassword = true;
result.removeClass();
result.addClass('good');
return 'Good';
} else {
validPassword = true;
result.removeClass();
result.addClass('strong');
return 'Strong';
}
}
function applyLowerAndUpperCaseFilter(password) {
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
return 1;
return 0;
}
function applyNumbersAndCharactersFilter(password) {
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))
return 1;
return 0;
}
function applySpecialCharacterFilter(password) {
if (password.match(/^([!%##$^*?_~]+)$/)) {
return 1;
} else if(password.match(/([&])/)) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
return 0;
}
function applyTwoSpecialCharacterFilter(password) {
if (password.match(/(.*[!,%,#,#,$,^,*,?,_,~].*[!,",%,#,#,$,^,*,?,_,~])/))
return 1;
else if(password.match(/([&])/))
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
return 0;
}
function applyAlphabeticalCharacterCriteria(password) {
var quality = 0;
var sequences = [
'abcdefghijklmnopqrstuvwxyz',
'01234567890',
'!\"§$%/()=?'
];
var proceed = true;
for(var i=0; i<(password.length-3); i++) {
for(var index = 0; index < sequences.length; index++) {
var needle = password.substring(i, 3);
if(stripos(sequences[index], needle) != false) {
quality -= 1;
proceed = false;
}
if(proceed == false) break;
}
if(proceed == false) break;
}
return quality;
}
function stripos(f_haystack, f_needle, f_offset) {
var haystack = (f_haystack + '')
.toLowerCase();
var needle = (f_needle + '')
.toLowerCase();
var index = 0;
if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
return index;
}
return false;
}
The messages and classes are for real time validation output only.
Rules:
The Password needs to be between 6 and 8 characters long.
It has to have at least 1 upper and 1 lower case character.
It has to have numbers.
It has to have at leats 1 special characters (2 give more value).
Only these special characters are allowed - _ . : , ; ! # § $ % / = ? #
The characters should not appear in a sequence if possible, so no abc,123,!§$ etc.

You have to anchor the first regex and add a quantifier:
if (password.match(/^([!,%,#,#,$,^,*,?,_,~]+)$/)) {
// here ^ ^ ^
The comma is not mandatory except if you want to match it:
if (password.match(/^([!%##$^*?_~]+)$/)) {

You can use indexOf method:
function applySpecialCharacterFilter(password) {
if (password.indexOf('&')>-1) {
throw new Error('Das Passwort enthält unerlaubte Zeichen.');
}
if (password.match(/^([!,%,#,#,$,^,*,?,_,~]+)$/)) {
return 1;
}
return 0;
}
and you need to change your Regexp according #M42 answer

Related

Inside the function >>> TypeError: Cannot read property 'length' of undefined

This is a code to validate a credit card number regarding to given requirements. I made the code in a way that fits all check functions in the main function and it is working well in that way. However I wanted to tidy up my code a bit and make it better practice so the code is like this now. I think I have a part of functions that I still couldn't understand fully. Can you please tell me what is my mistake here?
Any input appreciated.
'use strict';
let cardNumLength = getLength();
let isNumOnly = /^\d+$/.test(cardNum);
let isLastDigitEven = isEndEven();
let isSumValid = isSumGreaterThan16();
let allDigitsNotSame = allEqualCheck(cardNum);
let errorArray = [];
function cardNumValidator(cardNum) {
if (cardNumLength, isNumOnly, isLastDigitEven, isSumValid, allDigitsNotSame) {
console.log(`"${cardNum}" is a valid credit card number.`);
return
}
return errorArray;
}
// getLength function to check if the number has 16 digits
function getLength(cardNum) {
//console.log(cardNum.length); //debugging
if (cardNum.length == 16) {
return true;
}
return false;
}
// to check the final digit if its even
function isEndEven(cardNum) {
if (cardNum[cardNum.length - 1] % 2 == 0) {
return true;
}
return false;
}
// to check if the sum of the digits are greater than 16
function isSumGreaterThan16(cardNum) {
let intCardNum = parseInt(cardNum);
let sum = 0;
for (let i = 0; i < cardNum.length; i++) {
sum = parseInt(sum) + parseInt(cardNum[i]); //parseInt() converts string into number
}
if (sum > 16) {
return true;
}
return false;
}
function allEqualCheck(cardNum) {
if (cardNum.split('').every(char => char === cardNum[0])) {
return false;
}
return true;
}
/* using switch statement to final validation regarding to the requirements those checked seperately by previous inner functions*/
function isValidError() {
if (cardNumLength === false) {
errorArray.push('Number must be 16 digits!');
} else if (isNumOnly === false) {
errorArray.push('Invalid characters!');
} else if (isLastDigitEven === false) {
errorArray.push('Odd final number!');
} else if (isSumValid === false) {
errorArray.push('Sum less than 16!');
} else if (allDigitsNotSame === false) {
errorArray.push('All numbers can not be the same!');
}
return errorArray;
}
cardNumValidator('9999777788880000'); //valid number example
cardNumValidator('6666666666661666'); //valid number example
cardNumValidator('a92332119c011112'); //Invalid number example
cardNumValidator('4444444444444444'); //Invalid number example
cardNumValidator('1111111111111110'); //Invalid number example
cardNumValidator('6666666666666661'); //Invalid number example
In the very first line you are not passing any arguments to the getLength function.
I'm using global variables like you did, but set them depending on the cardNum.
The cardNumValidator function will now always return an error array, which will have length zero when there is no error. When there are multiple errors, the errorArray will have all of them, not just a single one.
'use strict';
let cardNumLength = false;
let isNumOnly = false;
let isLastDigitEven = false;
let isSumValid = false;
let allDigitsNotSame = false;
let errorArray = [];
function cardNumValidator(cardNum) {
cardNumLength = getLength(cardNum);
isNumOnly = /^\d+$/.test(cardNum);
isLastDigitEven = isEndEven(cardNum);
isSumValid = isSumGreaterThan16(cardNum);
allDigitsNotSame = allEqualCheck(cardNum);
errorArray = [];
isValidError();
if (errorArray.length == 0) {
console.log(`"${cardNum}" is a valid credit card number.`);
} else {
console.log(`"${cardNum}" is an invalid credit card number.`);
console.dir(errorArray);
}
return errorArray;
}
// getLength function to check if the number has 16 digits
function getLength(cardNum) {
//console.log(cardNum.length); //debugging
if (cardNum.length == 16) {
return true;
}
return false;
}
// to check the final digit if its even
function isEndEven(cardNum) {
if (cardNum[cardNum.length - 1] % 2 == 0) {
return true;
}
return false;
}
// to check if the sum of the digits are greater than 16
function isSumGreaterThan16(cardNum) {
let intCardNum = parseInt(cardNum);
let sum = 0;
for (let i = 0; i < cardNum.length; i++) {
sum = parseInt(sum) + parseInt(cardNum[i]); //parseInt() converts string into number
}
if (sum > 16) {
return true;
}
return false;
}
function allEqualCheck(cardNum) {
if (cardNum.split('').every(char => char === cardNum[0])) {
return false;
}
return true;
}
/* using switch statement to final validation regarding to the requirements those checked seperately by previous inner functions*/
function isValidError() {
if (cardNumLength === false) {
errorArray.push('Number must be 16 digits!');
}
if (isNumOnly === false) {
errorArray.push('Invalid characters!');
}
if (isLastDigitEven === false) {
errorArray.push('Odd final number!');
}
if (isSumValid === false) {
errorArray.push('Sum less than 16!');
}
if (allDigitsNotSame === false) {
errorArray.push('All numbers can not be the same!');
}
return errorArray;
}
cardNumValidator('9999777788880000'); //valid number example
cardNumValidator('6666666666661666'); //valid number example
cardNumValidator('a92332119c011112'); //Invalid number example
cardNumValidator('4444444444444444'); //Invalid number example
cardNumValidator('1111111111111110'); //Invalid number example
cardNumValidator('6666666666666661'); //Invalid number example

Can someone please tell me why this method did not work for finding palindromes?

Attempting to complete the algorithms on freeCodeCamp. I eventually found an approach that works, but i still don't understand why this method did not work for all cases.
function palindrome(str) {
var alphaNumericStr = str.replace(/\W/g,"");
var lowerCaseAlphaNumericString = alphaNumericStr.toLowerCase();
var arr = lowerCaseAlphaNumericString.split("");
arr.reverse();
var reversedString = arr.join("");
if(str === reversedString){
return true;
}
return false;
}
palindrome("race car");
You're comparing a string which has been stripped of spaces and converted to lowercase to the original string. Replace your conditional with:
if(lowerCaseAlphaNumericString == reversedString){
rethrn true;
}
return false;
Here's a little refactor if you're interested:
// ...
var reversedString = arr.join('');
return lowerCaseAlphaNumericString == reversedString;
demo
This is where you are going wrong if(str === reversedString)
Try this:
if(lowerCaseAlphaNumericString === reversedString) {
return true;
}
return false;
}
There could be another approach. In this approach, the corner cases are handled separately.
function check_Palindrome(input_str){
var astr = input_str.toLowerCase().replace(/\W/g,'');
var acount = 0;
if(astr==="") {
console.log("Not Palindrome.");
return false;
}
if ((astr.length) % 2 === 0) {
acount = (astr.length) / 2;
} else {
if (astr.length === 1) {
console.log("Palindrome.");
return true;
} else {
acount = (astr.length - 1) / 2;
}
}
for (var x = 0; x < acount; x++) {
if (astr[x] != astr.slice(-1-x)[0]) {
console.log("Not Palindrome.");
return false;
}
}
console.log("Palindrome.");
return true;
}

Regular Expressions for phone numbers and mobiles doesn'nt work correctly

I have a function for validating telephone and mobile numbers. Here is part of my function:
function IsPhone(){
var mob = /09[123]\d{8}$/;
var phn = /0\d{10}$/;
for (var i = 0; i < edit_rows.length; i++) {
if (edit_types[i] == 5) {
var phon_val = document.getElementById('phone1').value;
if (phon_val != "") {
if (phon_val.match(mob))
return true;
else if (phon_val.match(phn)) {
if ((phon_val).length == 11)
return true;
}
else {
msg_req += "Invalid format";
return false;
}
}
}
}
return true;
}
But it accepts all of these:
009153842716
09153842716
001234567890
01234567890
what can I do?
I think adding a ^ at the beginning of your expression would fix it. Your current query would match strings like 'thisisaninvalidvalue09153842716'. Adding the ^ makes sure you don't start with invalid input.

How to validate multiple fields at the same time using JQuery

I have created a form that validates using JQuery and JavaScript. The only problem is, would be that it validates one field at a time. So the user has to correct the first field first and then press submit again to see if the next field is valid.
What I would like to to do, is have the JQuery validate the whole form after pressing submit and show all the applicable error messages.
Here is My JS:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength < 4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
return false;
}
else
{
return true;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
return false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
return false;
}
else
{
return true;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if (fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
return false;
}
else
{
return true;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if (lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
return false;
}
else
{
return true;
}
}
function validateForm()
{
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
}
And here is my submit form code:
$('#your-form').submit(validateForm);
Instead of returning true or false return a string containing the error and an empty string if no error was found.
Then validateForm could be something like
function validateForm()
{
error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
...
if(error === ""){
return true;
}
$("#ErrorLname").text(error);
return false;
}
Working Fiddle
var validate;
function validateUserName()
{
validate = true;
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
validate = false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
validate = false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
validate = false;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
validate = false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
validate = false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
validate = false;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
validate = false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
validate = false;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
validate = false;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
validate = false;
}
}
function validateForm()
{
validateUserName();
validatePassword();
validateEmail();
validateFirstName();
validateLastName();
return validate;
}
You need to access all the fields and check if the field is valid r not. If the field is valid skip it, otherwise put the field in an array. When all the fields have been checked, then display the error fields from the array all at one time.

Where in the code to validate a phone number, in JavaScript orRazor?

This is my first webpage in which I prompt the user for a phone number to add to a Do Not Call List database. Everything is working so far but I need to add the following, which I can do following the advice in this answer
stripping the input from all characters except digits
validating that the resulting string is 10 digits long
Then, when telling the user that the number was added to the list, I want to present it in the (999) 999-9999 format.
Where should I add all that code? Iside the #{ } block? In JavaScript? Razor?
Check phone number
function IsNumber(s) {
var i, currentCharacter;
for (i = 0; i < s.length; i++) {
// Check that current character is number.
currentCharacter = s.charAt(i);
if (((currentCharacter < "0") || (currentCharacter > "9"))) {
return false;
}
}
// All characters are numbers.
return true;
}
function TestInternationalPhone(strPhone) {
var bracket = 3,
openBracket,
phoneNumberOnly,
phoneNumberDelimiters = "()- ",
validWorldPhoneChars = phoneNumberDelimiters + "+",
minDigitsInIPhoneNumber = 10;
strPhone = SOS.StringHelper.Trim(strPhone);
if (strPhone.length === 0) {
return false;
}
if (strPhone.indexOf("+") > 1) {
return false;
}
if (strPhone.indexOf("-") != -1) {
bracket = bracket + 1;
}
if (strPhone.indexOf("(") != -1 && strPhone.indexOf("(") > bracket) {
return false;
}
openBracket = strPhone.indexOf("(");
if (strPhone.indexOf("(") != -1 && strPhone.charAt(openBracket + 2) != ")") {
return false;
}
if (strPhone.indexOf("(") == -1 && strPhone.indexOf(")") != -1) {
return false;
}
phoneNumberOnly = SOS.StringHelper.StripCharsInBag(strPhone, validWorldPhoneChars);
return (IsNumber(phoneNumberOnly) && phoneNumberOnly.length >= minDigitsInIPhoneNumber);
}

Categories