Error in validating my password with Javascript - javascript

I am trying to check my user inputted password with a series of if statements and boolean variables within a function. It seems like my if statements are not modifying my boolean variables. Could someone tell me why?
I was trying to use (/[a-zA-z]/).test(pValue.charAt(0))) as a boolean to see if the first character entry was a lower or upper case letter, but that didn't work either.
document.querySelector("#enter").addEventListener("click", validate);
function validate(e) {
var count = false;
var firstChar = false;
var hasNum = false;
var special = false;
var pValue = document.querySelector("#passwrd").value;
var pLength = pValue.length;
console.log(pValue);
console.log(pLength);
if(pLength > 4 && pLength <= 8) {
count = true;
}
if(pValue.search(e.charCode === [65 - 90]) === 0) {
firstChar = true;
}
console.log(firstChar);
for(var j = 0; j < pLength; j++) {
if(pValue.charAt(j) == "$" || pValue.charAt(j) == "%" || pValue.charAt(j) == "#") {
special = true;
}
}
for(var i = 0; i < pLength; i++) {
if(!isNaN(pValue.charAt(i))) {
hasNum = true;
}
}
if(count && firstChar && hasNum && special) {
document.querySelector("#show_word").textContent = pValue;
}
}

Related

making custom validation for password field in react

I am making a custom registration page with only 2 values Email and Password, later I will add confirm password as well, for my password field I have some restrictions and I am using some regex and also some custom made code to make the validation.
this is my validateField:
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
let passwordValid = this.state.passwordValid;
//let passwordValidConfirm = this.state.passwordConfirmValid;
switch(fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)#([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? '' : ' is invalid';
break;
case 'password':
passwordValid = (value.length >= 5 && value.length <= 32) && (value.match(/[i,o,l]/) === null) && /^[a-z]+$/.test(value) && this.check4pairs(value) && this.check3InRow(value);
fieldValidationErrors.password = passwordValid ? '': ' is not valid';
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid,
//passwordValidConfirm: passwordValidConfirm
}, this.validateForm);
}
as you can see for
passwordValid
I have made some methods, this one
check3InRow
doesnt work the way I want it to work, this one makes sure, you have at least 3 letters in your string that are in a row so like "abc" or "bce" or "xyz".
check3InRow(value){
var counter3 = 0;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if((lastC + 1) === value.charCodeAt(i)){
counter3++;
if(counter3 >= 3){
alert(value);
return true;
}
}
else{
counter3 = 0;
}
lastC = value.charCodeAt(i);
}
return false;
}
this doesnt work correctly so it should accept this:
aabcc
as a password but not:
aabbc
You are starting your counter from 0 and looking for greater than equal to 3 which will never be 3 for 3 consecutive characters. Rest everything is fine with your code.
check3InRow(value) {
var counter3 = 1;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
alert(value);
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}
Can we not do a simple version of that function? Like
function check3InRow2(value){
for (var i = 0; i < value.length-2; i++) {
const first = value.charCodeAt(i);
const second = value.charCodeAt(i+1);
const third = value.charCodeAt(i+2);
if(Math.abs(second - first) === 1 && Math.abs(third-second) === 1){
return true;
}
}
return false;
}
I mean complexity wise it is O(N) so maybe we can give this a try
Also adding the your function. When you are AT a char then you should consider counter with 1. Because if another one matches it will be 2 consecutive values.
function check3InRow(value) {
var counter3 = 1;
var lastC = value.charCodeAt(0);
for (var i = 1; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}

mask work for id but not for class

hi i have a problem with my javascript code it works for input by id but i wat to use it on class element. I do not know what is i am doing wrong any idea? I paste my code
i want to mask time on my input
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
var value = $(text).val(); //text.value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
$(text).val() = ""; //text.value = "";
return;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text.val() = newValue;
//text.value = newValue;
} catch (e) { }
}
getElementById returns a single DOMElement while getElementsByClass returns an array of elements. To allow for both, you could have one function that accepts a DOMElement and two functions that find the elements, one for id and one for class:
function maska(elem, mask, evt) {
try {
var value = $(elem).val();
// blah blah, rest of the function
}
function maskById(id, mask, evt) {
var element = document.getElementById(id);
maska(element, mask, evt);
}
function maskByClass(class, mask, evt) {
var element_list = document.getElementsByClass(class);
for(var i = 0; var i < element_list.length; i++) {
maska(element_list[i], mask, evt);
}
}
But you would be better off using the jquery selector combined with .each , which always returns results as a set/array, regardless of selector type.
document.getElementById returns a single element, which your code is written to handle.
document.getElementsByClassName returns multiple elements. You need to loop over them and process them each individually.
I don't get why you use getElementsByClassName and then use jQuery features?
try $('input.' + inputName)
getElementById returns a single element, while getElementsByClassName returns a collection of elements. You need to iterate over this collection
function maska(inputName, mask, evt) {
var text = document.getElementsByClassName(inputName);
try {
for (var i = 0; i < text.length; i++) {
var value = text[i].value;
// Jeśli ktoś naciśnie dela lub backspace to czyszcze inputa
try {
var e = (evt.which) ? evt.which : event.keyCode;
if (e == 46 || e == 8) {
text[i].value = "";
continue;
}
} catch (e1) { }
var literalPattern = /[0\*]/;
var numberPattern = /[0-9]/;
var newValue = "";
for (var vId = 0, mId = 0; mId < mask.length; ) {
if (mId >= value.length)
break;
// Wpada jakaś inna wartość niż liczba przechowuje tylko ta dobra wartosc
if (mask[mId] == '0' && value[vId].match(numberPattern) == null) {
break;
}
// Wpadł literał
while (mask[mId].match(literalPattern) == null) {
if (value[vId] == mask[mId])
break;
newValue += mask[mId++];
}
var godzina = value.substr(0, 2);
var minuty = value.substr(3,4);
if (minuty > '59' || godzina > '23') {
break;
}
else
newValue += value[vId++];
mId++;
}
text[i].value = newValue;
}
} catch (e) { }
}

Remove Required Field from QuickCreate in Sugarcrm

I wrote a function to remove accounts name relate field from Contacts QuickCreate but my function works in Firefox perfectly but in chrome its not working... Here is my function
function manageRequired(reqArr, disabledVal)
{
var requiredLabel = '<span class="required">*</span>'; // for firefox
var search_requiredLabel = '<span class="required"'; // searching string for firefox
var form = "";
for(var i = 0; i < document.forms.length; i++)
{
if(document.forms[i].id=='EditView')
{
form = 'EditView';
break;
}
if(document.forms[i].id=='form_SubpanelQuickCreate_Contacts')
{
form = 'form_SubpanelQuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Contacts')
{
form = 'form_QuickCreate_Contacts';
break;
}
if(document.forms[i].id=='form_QuickCreate_Accounts')
{
form = 'form_QuickCreate_Accounts';
break;
}
}
for(var j = 0; j < reqArr.length; j++)
{
var flag = true;
if (validate[form] != 'undefined')
{
for(var i = 0; i < validate[form].length; i++)
{
if(validate[form][i][0] == reqArr[j].id && validate[form][i][2])
{
if(disabledVal)
{
flag = false;
break;
}
else
{
validate[form][i][2] = false;
}
}
}
}
var labelNode = document.getElementById(reqArr[j].id + '_label');
if(flag & disabledVal)
{
// we require the field now
addToValidate(form, reqArr[j].id, reqArr[j].type, true,reqArr[j].label );
}
if(disabledVal)
{
if(labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1) // for IE replace search string
{
search_requiredLabel = '<SPAN class=required>';
}
if (labelNode != null && labelNode.innerHTML.indexOf(search_requiredLabel) == -1)
{
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
labelNode.innerHTML = labelNode.innerHTML + requiredLabel;
}
}
else
{
if(labelNode != null)
{
if(labelNode != null && labelNode.innerHTML.indexOf("<SPAN class=required>*</SPAN>") == -1 && labelNode.innerHTML.indexOf('<span class="required">*</span>') == -1 )// for that field which is unrequired
{
}
else if(labelNode != null && labelNode.innerHTML.indexOf(requiredLabel) == -1) // for IE replace span string
{
requiredLabel = "<SPAN class=required>*</SPAN>";
}
labelNode.innerHTML = labelNode.innerHTML.replace(requiredLabel, '');
}
}
}
}
Can anyone please help me out to solve this issue...
To remove a required field from QuickCreate in Sugarcrm you can use this fuction:
removeFromValidate('EditView','eventlist_c');
or remove remove the validtion applied to the field:
$('#eventlist_c_label').html('{$mod_strings['LBL_EVENTLIST']}: ');

"Unable to get value of the property 'style'" when trying to change style in IE

Have written a function for cycling through the questions in a online quiz. I works fine in every browser but IE (god I wish IE would just curl up and die). Function is below.
function cycleQs() {
var qs = document.getElementsByName("quizQ");
var nextQBtn = document.getElementById("btnNextQ");
var i = 0;
var curQ = -1;
for (i = 0; i < qs.length; i++) {
if (qs[i].style.display == "block") {
curQ = i;
}
//qs[i].style.display = "none";
}
var valid = false;
if (curQ > -1) {
var qId = qs[curQ].id.replace("dv", "");
var inps = document.getElementsByName(qId);
if (inps.length > 0) {
if (inps[0].type == "radio") {
for (i = 0; i < inps.length; i++) {
if (inps[i].checked) {
valid = true;
}
}
} else if (inps[0].type == "hidden") {
valid = true;
for (i = 0; i < inps.length; i++) {
if (inps[i].value <= 0) {
valid = false;
}
}
}
} else {
valid = true;
}
} else {
valid = true;
}
if (valid == true) {
for (i = 0; i < qs.length; i++) {
qs[i].style.display = "none";
}
if (curQ < (qs.length - 1)) {
qs[curQ + 1].style.display = "block";
if (curQ == (qs.length - 2)) {
var scoreDv = document.getElementById("dvScore");
nextQBtn.style.display = "none";
var answers = getAnswers();
//alert(answers)
scoreDv.innerHTML = "Processing";
processResults(answers);
}
} else {
qs[0].style.display = "block"; // Problem occurs here when function first loads
}
} else {
alert("You must select an answer before you can proceed");
}
}
Any ideas of a work around for this?
document.getElementsByName is likely not returning anything, because of IEs implementation: see here
so qs[0] probably doesn't exist

Javascript Phone number validation Paratheses sign

I did some searching and there where others asking this question and answers to it but none that seemed to fit what I was trying to do. Basically I'm working on a validation of the phone entry that accepts (123)4567890 as an entry. I've already implemented one that accepts a simple number string such as 1234567890 and one with dashes 123-456-7890. I know I'm making a simple mistake somewehre but I can't figure out what I'm doing wrong.
Here's the phone number with dashes form that is working:
//Validates phone number with dashes.
function isTwelveAndDashes(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 3 || i == 7) {
if (c != '-') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
and this is the one I can't manage to work out.
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
var pass = true;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') {
pass = false;
}
}
if (i == 4) {
if (c != ')') {
pass = false;
}
}
else {
if (!isDigit(c)) {
pass = false;
}
}
}
return pass;
}​
You can do it very easily with regex:
return !!phone.match(/\(\d{3}\)\d{7}/g)
Live DEMO
Update:
The code you had didn't work because you forgot the else if:
else if (i == 4) { // Added the "else" on the left.
Checking phone number with RegEx is certainly the way to go. Here is the validation
function that ignores spaces, parentheses and dashes:
check_phone(num) {
return num.replace(/[\s\-\(\)]/g,'').match(/^\+?\d{6,10}$/) != null}
You can vary the number of digits to accept with the range in the second regular expression {6,10}. Leading + is allowed.
Something like that (a RegExp rule) can make sure it matches either rule.
var numbers = ['(1234567890','(123)4567890','123-456-7890','1234567890','12345678901'];
var rule = /^(\(\d{3}\)\d{7}|\d{3}-\d{3}-\d{4}|\d{10})$/;
for (var i = 0; i < numbers.length; i++) {
var passed = rule.test(numbers[i].replace(/\s/g,''));
console.log(numbers[i] + '\t-->\t' + (passed ? 'passed' : 'failed'));
}
EDIT:
function isDigit(num) {
return !isNaN(parseInt(num))
}
function isTwelveAndPara(phone) {
if (phone.length != 12) return false;
for (var i = 0; i < phone.length; i++) {
var c = phone.charAt(i);
if (i == 0) {
if (c != '(') return false;
} else if (i == 4) {
if (c != ')') return false;
} else if (!isDigit(c)) return false;
}
return true;
}
// or...
function isTwelveAndPara(phone) {
if (phone.length != 12 || phone.charAt(0) != '(' || phone.charAt(4) != ')') return false;
for (var i = 1; i < phone.length, i != 4; i++) {
if (!isDigit(phone.charAt(i))) return false;
}
return true;
}

Categories

Resources