Password with regular password - javascript

I have to do the password by this condition for creating password to follow this characteristics :
Contain at least 12 alphanumeric characters.
Contain both upper and lower case letters.
Contain at least one number (for example, 0-9).
Contain at least one special character (for example,!$%^&*()_+|~-=`{}[]:";'<>?,/).
i did this :
<input type="password" required pattern="^(?=.*[a-zA-Z])(?=.*\d)(?=.*
[!##$%^&*()_+])[A-Za-z\d][A-Za-z\d!##$%^&*{}()_=+]{12,}$"
name="password"
nblur="this.setCustomValidity(this.validity.patternMismatch
? 'Password must contain at least 12 characters, including upper
lowercase numbers and least special character' : '');
if(this.checkValidity()) form.password1.pattern = this.value;">
but when i try to put a password and confirm it always return not valid password
Sorry for this question, but with regExpression i put for this characteritics. Thanks in advance.

Write a series of test in JavaScript and control the submit event for your form.
var testPassword = (function() {
var allTests = [];
var minimumAlphaNumericCharacters = 12;
function countAlphanumeric(password) {
var count = password.length - password.replace(/[a-z]|\d/ig, '').length;
if (count < minimumAlphaNumericCharacters) {
return "Too few Alphanumeric Characters! At least " + minimumAlphaNumericCharacters + " nedded, " + count + " found";
}
return true;
}
allTests.push(countAlphanumeric);
function containsUpperAndLowerCharacters(password) {
var test = (password === password.toLowerCase());
if (test) {
return "Must contain both upper and lower case characters";
}
return true;
}
allTests.push(containsUpperAndLowerCharacters);
var minimumDigits = 1;
function containsMinimumDigits(password) {
var test = password.replace(/\D/ig, '').length;
if (test < minimumDigits) {
return "Must contain at least " + minimumDigits + " digits, " + test + " digits found";
}
return true;
}
allTests.push(containsMinimumDigits);
var minimumSpecials = 1;
function containsMinimumSpecials(password) {
var test = password.replace(/\w/ig, '').length;
if (test < minimumSpecials) {
return "Must contain at least " + minimumSpecials + " special symbols, " + test + " special symbols found";
}
return true;
}
allTests.push(containsMinimumSpecials);
return function testPassword(password) {
return allTests
.map(function(test) {
return test(password);
})
.filter(function(test) {
return test !== true;
});
};
})();
//TEST
var form = document.body.appendChild(document.createElement("form"));
var input = form.appendChild(document.createElement("input"));
var output = document.body.appendChild(document.createElement("pre"));
input.onchange = input.onkeyup = form.onsubmit = function(evt) {
var password = input.value.toString();
var test = testPassword(password);
output.textContent = test.join("\n");
if (evt.type == "submit") {
alert((test.length < 1 ? "Good" : "Bad") + " Password");
}
return false;
};

Related

How to validate textfield with 0 to 59, it will allow 1,2,3,*/59

I need to validate Textbox for this test cases.
It will allow 0 to 59 no characters and special character not allowed except *,/
It will allow 1,2,3,4 but 1,2,3,60 should not allow
It will allow /59 or 1,2,3,4,/59 but 1,2,3,5,*/59/19 should not allow
i tried,
var input = document.getElementById('configMinute').value;
//console.info("Else Called");
var slashPattern = "/";
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
var getStringCheck = checkSpecialChar(input,specialChars);
if(getStringCheck==true){
// string = 1,2,3,*/10
// ,*/
var getStringValues = input.split(',');
var notAllowedCharPattern = "<>#!#$%^&()_+[]{}?:;|'\"\\.~`-=";
var allowedChar = checkSpecialChar(input,notAllowedCharPattern);
if(allowedChar==false){
console.info(getStringValues);
getStringValues.forEach(function(element){
//string = 1 2 3 */10
var validateSlash = checkSpecialChar(element,slashPattern);
if(element.startsWith("*")==true){
var newInput = element.split('/');
console.info("newInput: "+ element);
newInput.forEach(function(element) {
console.info("newInput Foreach: "+ element);
if(element=='*' || (element>=0 && element <=59)){
return true;
}
else{
alert("Please enter numbers between 0 to 59 or '*' ==>1");
document.getElementById('configMinute').focus();
return false;
}
});
}else{
console.info("* Else: "+ element);
if(element=='*' || (element>=0 && element <=59)){
return true;
}else{
alert("Please enter numbers between 0 to 59 or '*' ==>1");
document.getElementById('configMinute').focus();
return false;
}
}
});
}else{
alert ("File name has special characters \nAllowed Characters are *,/ ==>3");
document.getElementById('configMinute').focus();
return false;
}
}else if(input == '*' || (input>=0 && input <=59)){
return true;
}else{
alert("Please enter numbers between 0 to 59 or '*' ==>4");
document.getElementById('configMinute').focus();
return false;
}
Thanks in advance
You could try a regex like
(?:(?:^|,)(?:[1-5]?\d|\*?\/59)\b)+$
It matches the beginning of the line (^) or a , followed by either a number, 0-59, or /59 optionally preceded by a *. And this pattern can then repeat any number of times, until the end of the line.
See it here at regex101.

How to check if number and has nine characters?

how do I check if a text entered is a number and has nine characters in javascript?
Intengo do with the code below but shows me correctly.
function numberValidate(idtelf){
var number = document.getElementById('idtelf');
var charactersLength = number.value.length;
if(isNaN(number) || charactersLength !=9 )
{
alert( "Enter a valid number ");
}
else {
alert( "correct");
}
};
This one checks also if it's a number. Other answers would accept "123456 " (3 spaces at the end) as well.
function numberValidate(idtelf){
var input = document.getElementById('idtelf');
var number = parseFloat(input.value);
var charactersLength = input.value.length;
var numberLength = (""+number).length;
if(isNaN(number) || charactersLength !=9 || numberLength !=9 )
{
alert( "Enter a valid number ");
}
else {
alert( "correct");
}
};
If number can'n be float then instead of parseFloat() use parseInt()
You can use
HTML
<input id="idtelf">
Javscript
var number1 = document.getElementById('idtelf');
number1.onblur = function () {
var charactersLength = number1.value.replace(/\s/gi,"").length;
if(isNaN(number1.value) || charactersLength != 9)
{
alert("Enter a valid number ...");
}
else {
alert("correct");
}
};
https://jsfiddle.net/rreyaovy/5/
Try this..This handles all type of input..
function numberValidate(idtelf){
var input = document.getElementById('idtelf');
var number = input.value.toString();
var myString = number.replace(/\D/g,'');
if(number.length ==9 && number.length == myString.length)
{
alert( "Correct");
}
else {
alert( "Enter a valid number");
}
};
Demo
Here's a function that uses a simple regular expression to test if the value is a 9-digit number.
function numberValidate(id){
var number = document.getElementById(id).value,
regex = /^[0-9]{9}$/;
if (regex.test(number)) {
return true;
} else {
return false;
}
};
We can use this function like this:
function numberValidate(id){
var number = document.getElementById(id).value,
regex = /^[0-9]{9}$/;
if (regex.test(number)) {
return true;
alert();
} else {
return false;
}
};
var result1 = numberValidate('testNum1');
var result2 = numberValidate('testNum2');
var result3 = numberValidate('testNum3');
document.getElementById('result').innerHTML = 'Input 1: ' + result1 + '<br/>Input 2: ' + result2 + '<br/>Input 3: ' + result3;
<input id="testNum1" value="1234">
<input id="testNum2" value="123456789">
<input id="testNum3" value="1234567891011">
<div id="result"></div>
try like this
if(isNaN(number.value) || charactersLength !=9 )
instead of this
if(isNaN(number) || charactersLength !=9 )

Try and catch for check sum validation on input to check three parts of an input in Javascript

Bouncing my head off the wall here trying to figure out a better way to handle this. I have a large input value which has three checks to check the sum of certain parts of the string in order to validate it. I'm using three try/catch blocks in one function to run the check right now and it seems to be working except for the final validation check which always seems to return true. What I'm wondering is a) is this a good method to use, b) is there a cleaner way to do this with for loop and c) why my final check is not doing anything. Any help is appreciated. I have access to jQuery and Underscore.js if that helps but I have not worked much with underscore. I made a fiddle here:
Sample Fiddle
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
// run the checksum
var valid = false;
try {
var sum = (parseInt(number[0]) * 7) +
(parseInt(number[1]) * 3) +
(parseInt(number[2])) +
(parseInt(number[3]) * 7) +
(parseInt(number[4]) * 3) +
(parseInt(number[5])) +
(parseInt(number[6]) * 7) +
(parseInt(number[7]) * 3) +
(parseInt(number[8]));
alert(((sum % 10).toFixed(0)));
var checkDigit = ((sum % 10).toFixed(0));
if ((number[9]) === ("" + checkDigit)) {
alert('Our Checkdigit is valid', checkDigit);
valid = true;
}
} catch (e) {
alert('Fail for check 1!');
valid = false;
}
try {
var sum2 = (parseInt(number[13]) * 7) +
(parseInt(number[14]) * 3) +
(parseInt(number[15])) +
(parseInt(number[16]) * 7) +
(parseInt(number[17]) * 3) +
(parseInt(number[18]));
alert(((sum2 % 10).toFixed(0)));
var checkDigit2 = ((sum2 % 10).toFixed(0));
if ((number[19]) === ("" + checkDigit2)) {
alert('Our Checkdigit2 is valid', checkDigit2);
valid = true;
}
} catch (e) {
alert('Fail for check 2!');
valid = false;
}
try {
var sum3 = (parseInt(number[21]) * 7) +
(parseInt(number[22]) *3) +
(parseInt(number[23])) +
(parseInt(number[24]) * 7) +
(parseInt(number[25]) * 3) +
(parseInt(number[26]));
alert(((sum3 % 10).toFixed(0)));
var checkDigit3 = ((sum3 % 10).toFixed(0));
if ((number[27]) === ("" + checkDigit3)) {
alert('Our Checkdigit3 is valid',checkDigit3);
valid = true;
}
} catch (e) {
valid = false;
}
alert('All Good DUde!');
return valid;
}
Here is the way to do it.
I have not thrown any error, only error can be if the number is not parseable and so you can throw it if you like else if your sum checks can validate that should be good enough
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
var valid = false;
//try{
var sum1 = returnSum(number,[0,1,2,3,4,5,6,7,8],[7,3,1,7,3,1,7,3,1]);
var sum2 = returnSum(number,[13,14,15,16,17,18],[7,3,1,7,3,1]);
var sum3 = returnSum(number,[21,22,23,24,25,26],[7,3,1,7,3,1]);
/*
//only if you are throwing err
}catch(e){
valid = false;
}
*/
if (number[9] === sum1 && number[19] === sum2 && number[27] === sum3) {
console.log(sum1 +'|' + sum2 + '|' + sum3);
valid = true;
}
console.log('All Good DUde!');
return valid;
}
function myParse(n){
return (isNaN(parseInt(n,10))) ? -1 : parseInt(n,10);
}
function returnSum(n,ind,mul){
var acc = 0;
var pNum = 0;
for(var i=0; i<ind.length; i++){
pNum = myParse(n[ind[i]]);
if(pNum == -1){
pNum=0;
//throw 'error';//if you really want to throw error on not a number / or your number should fail
}
acc += pNum * mul[i];
}
return (acc%10).toFixed(0)+'';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3> Sample test number to use -- copy and paste should work </p=h3>
<p>487013675311199070109160101300</p>
<input id="searchTxt" placeholder="add numbers together">
<div id='numberValue'>Number goes here</div>
Cheers. joy
From experience, you may want to separate as much math as possible in your try block. JavaScript has a weird way of handling variables and may not be doing what you think it is.

validate password length after user leave password field

I want to check if the password length is at least 8 characters or not, when the user leaves the password field or press tab key.
How can i do this?
My code for password is shown below.
<input type="password" name="password" id="pass1" placeholder="password"/>
Use the jquery blur method for this.
$('#pass1').on('blur', function(){
if(this.value.length < 8){ // checks the password value length
alert('You have entered less than 8 characters for password');
$(this).focus(); // focuses the current field.
return false; // stops the execution.
}
});
Fiddle for Demo
You can use javascript onchange event as below
and script code callfunction() as
function callfunction()
{
var textBox = document.getElementById("pass1");
var textLength = textBox.value.length;
if(textBox.value=='' || textLength<=8)
{
alert('Please enter correct password');
}
}
try this:
$('#pass1').on('blur', function(){
if($(this).val().length > 8){
alert('safe!');
}
});
here is an example: http://jsfiddle.net/ACK2f/
Password validation can use several rules, I used a service but the code inside the function can be reusable:
_validatePassword = function (validateUserNameRules, Model)
{
//bolean parameter validateUserNameRules -> true/false
//this method recive a model like this:
//Model.userName -> string
//Model.password -> string
//Model.password2 -> String
var validationResult = {
ResultId: 1, //1 success
Message: "Password is correct."
};
if (validateUserNameRules && Model.userName == "") {
validationResult.ResultId = 2;
validationResult.Message = "Error: User name cannot be blank.";
return (validationResult);
}
var re = /^\w+$/;
if (validateUserNameRules && !re.test(Model.userName)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Username must contain only letters, numbers and underscores.";
return (validationResult);
}
if (Model.password != "" && Model.password == Model.password2) {
if (Model.password.length < 6) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must contain at least six characters.";
return (validationResult);
}
if (validateUserNameRules && Model.password == Model.userName) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must be different from the Account Name.";
return (validationResult);
}
re = /[0-9]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one number (0-9).";
return (validationResult);
}
re = /[a-z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one lowercase letter (a-z).";
return (validationResult);
}
re = /[A-Z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one uppercase letter (A-Z).";
return (validationResult);
}
} else {
validationResult.ResultId = 2;
validationResult.Message = "Error: Please check that you've entered and confirmed your password.";
return (validationResult);
}
return (validationResult); //success password validation!!
};

Ensuring that an entered name doesn’t end with a space

I am trying to get it so that if I type in a name that ends with a space, the textfield will go red. Most of the code works its just one method does not seem to be working.
The issue must be somewhere in the last index part?
var NamePass = true;
function ValidateName() {
var BlankPass = true;
var GreaterThan6Pass = true;
var FirstBlankPass = true;
var BlankMiddleName = true;
if (document.getElementById('Name').value == "") {
BlankPass = false;
}
var Size = document.getElementById('Name').value.length;
console.log("Size = " + Size);
if (Size < 7) {
GreaterThan6Pass = false;
}
if (document.getElementById('Name').value.substring(0, 1) == " ") {
FirstBlankPass = false;
}
var LastIndex = document.getElementById('Name').value.lastIndexOf();
if (document.getElementById('Name').value.substring((LastIndex - 1), 1) == " ") {
FirstBlankPass = false;
}
string = document.getElementById('Name').value;
chars = string.split(' ');
if (chars.length > 1) {} else
BlankMiddleName = false;
if (BlankPass == false || GreaterThan6Pass == false || FirstBlankPass == false || BlankMiddleName == false) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
http://jsfiddle.net/UTtxA/10/
lastIndexOf gets the last index of a character, not the last index in a string. I think you meant to use length instead:
var lastIndex = document.getElementById('Name').value.length;
Another problem with that, though, is that substring takes a start and end index, not a start index and a substring length. You could use substr instead, but charAt is easier:
if (document.getElementById('Name').value.charAt(lastIndex - 1) == " ") {
FirstBlankPass = false;
}
Now, for some general code improvement. Instead of starting with all your variables at true and conditionally setting them to false, just set them to the condition:
var NamePass = true;
function ValidateName() {
var value = document.getElementById('Name').value;
var BlankPass = value == "";
var GreaterThan6Pass = value.length > 6;
var FirstBlankPass = value.charAt(0) == " ";
var LastBlankPass = value.charAt(value.length - 1) == " ";
var BlankMiddleName = value.split(" ").length <= 1;
if (BlankPass || GreaterThan6Pass || FirstBlankPass || LastBlankPass || BlankMiddleName) {
console.log("BlankPass = " + BlankPass);
console.log("GreaterThan6Pass = " + GreaterThan6Pass);
console.log("FirstBlankPass = " + FirstBlankPass);
console.log("BlankMiddleName = " + BlankMiddleName);
NamePass = false;
document.getElementById('Name').style.background = "red";
} else {
document.getElementById('Name').style.background = "white";
}
}
A couple more points of note:
It’s probably a good idea to use camelCase variable names instead of PascalCase ones, the latter usually being reserved for constructors
blah == false should really be written as !blah
An empty if followed by an else can also be replaced with if (!someCondition)
That function looks like it should return true or false, not set the global variable NamePass
Penultimately, you can sum this all up in one regular expression, but if you intend to provide more specific error messages to the user based on what’s actually wrong, then I wouldn’t do that.
function validateName() {
return /^(?=.{6})(\S+(\s|$)){2,}$/.test(document.getElementById('name').value);
}
And finally — please keep in mind that not everyone has a middle name, or even a name longer than 6 characters, as #poke points out.

Categories