Enforce strong password policy with parsley.js - javascript

I have a password field that i will like to ensure that the users input a password that will meet the criteria stated below:-
Must contain at least one capital letter
Must contain at least one small letter
Must contain a number and lastly
A special character like #%#!*(()+= ( optional )
I have tried to use the data-parsley-pattern, and data-parsley-type but not getting the required results.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.6.0/parsley.js"></script>
<form data-parsley-validate>
<input type="password" name="password" id="password" minlength="6" data-parsley-type="alphanum" data-parsley-pattern="^/^[a-zA-Z0-9\-\_]$/" class="form-control allForms" required data-parsley-required-message="Your password" data-parsley-trigger="change focusin" placeholder="Enter password">
</form>

I think that for efficiency and maintainability you should either define a custom validator like explained here or a regex one if you're good at it (((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?(?=.*[#%#!*(()+=]))).{6,16} could do the job?);)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.6.0/parsley.js"></script>
<form data-parsley-validate>
<input type="password" name="password" id="password" minlength="6" data-parsley-type="alphanum" data-parsley-pattern="^/^[a-zA-Z0-9\-\_]$/" class="form-control allForms" required data-parsley-required-message="Your password" data-parsley-trigger="change focusin" placeholder="Enter password">
</form>

Related

why is my validation in password not working when connected with html page?

I have created a javascript page and connected it with html page. In the Javascript, i have created validation of the password and if there is a password mismatch then it will alert that there is a mismatch.
function validation()
{
if(password==repassword){
console.log(" ");
}
else{
alert(" ");
}
}
Above code is the javascript code and below is the html code.
LogIn
<label for="username">First Name: </label>
<input class="firstname" type="text" id="firstname" placeholder="First name"><br>
<label for="username">Last Name: </label>
<input class="lastname" type="text" id="lastname" placeholder="Last name"><br>
<label for="email">Email id: </label>
<input class="email" type="email" id="email" placeholder="Email id"><br>
<label for="labeltext">Password: </label>
<input class="password" type="password" id="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>
<label for="labeltext">Re-Password: </label>
<input class="Re-Password" type="password" id="repassword" placeholder="Re-Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>
<button class="Submit" onclick="validation()">Submit</button>
<button class="reset">Reset</button>
</form>
Does anyone know what's wrong in my code? Thank you!
You must create a reference for each element in javascript:
const password = document.getElementById('password');
const repassword = document.getElementById('repassword');
Now your variables are not local and you can use them in your function:
function validation()
{
if(password.value==repassword.value){
console.log(" ");
}
else{
alert(" ");
}
}
I believe what you want to do is to check if the password matches the verify password value.
From your javascript codes, everything looks good but if it is not working, then there is a problem with your HTML elements IDs i.e password field id and verify password field id. Check if you are making a mistake in any of the code you are using to get the element values.
A little mistake like
var x = document.getElementById("txtpass").value;
Where as, in your HTML source, there is no such element with txtpass as id could cause your javascript codes to break.
I would advise you post the complete HTML and Javascript codes.
Better still, use your browser console to check for the runtime error that is depriving your code from running as expected.
Use name=password in your password and name=repassword in your repassword tag like
<input class="password" name="password" type="password" id="password" placeholder="Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"><br><br>

pattern() function and onkeyup() function not working together

i am trying to let the screen show that the password inserted should be in a certain regex with pattern when typing in the fields but when i used onkeyup() to check if both passwords are matching the part with the onkeyup works but
the pattern info box doesnt show up anymore
so i was hoping to know why its not working ,if both functions are not allowed together or anything
here is the html
<div class ="signupbox">
<h1>Signup</h1>
<form action="">
<p>Username</p>
<input type="text" id="user" placeholder="Enter Username" pattern="^[a-zA-Z0-9]{8,}$" title="please enter a username with only Letters and numbers[0-9]">
<p>Password</p>
<input name="password" id="password" type="password" placeholder="Enter Password" pattern="(?=.*[a-zA-Z].*)(?=.*[A-Z])(?=.*[0-9])(?=.*[##!%])[a-zA-Z0-9##!%]{6,}" title="please enter a password with at least 1 capital letter and one special from[##!%]" onkeyup='check();'/>
<p>confirm password</p>
<input type="password" name="confirm_password" id="confirm_password" placeholder="confirm Password" onkeyup='check();' />
<span id='message'></span>
<br>
<input type="submit" id="Signup" disabled value="Signup" >
</form>
here is the js
var check = function() {
if (document.getElementById('password').value ==
document.getElementById('confirm_password').value) {
document.getElementById('message').style.color = 'rgb(1, 126, 11)';
document.getElementById('message').style.fontSize="20px"
document.getElementById('message').innerHTML = "Passwords are matching";
} else {
document.getElementById('message').style.color = 'rgba(255, 0, 0, 0.829)';
document.getElementById('message').style.fontSize="20px"
document.getElementById('message').innerHTML = "Passwords are not matching";
sign.disabled=true;
}
}
Simply adding oninput="this.reportValidity()" to all input fields with a pattern, in addition to your onkeyup='check();', will show the browser-based validation feedback.

How to not refresh after pressing submit [duplicate]

Is there a way to require the entries in two form fields to match using HTML? Or does this still have to be done with JavaScript? For example, if you have two password fields and want to make sure that a user has entered the same data in each field, are there some attributes, or other coding that can be done, to achieve this?
Not exactly with HTML validation but a little JavaScript can resolve the issue, follow the example below:
function check() {
var input = document.getElementById('password_confirm');
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
<p>
<label for="password">Password:</label>
<input name="password" required="required" type="password" id="password" oninput="check()"/>
</p>
<p>
<label for="password_confirm">Confirm Password:</label>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check()"/>
</p>
<input type="submit" />
You can with regular expressions Input Patterns (check browser compatibility)
<input id="password" name="password" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" placeholder="Password" required>
<input id="password_two" name="password_two" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Verify Password" required>
A simple solution with minimal javascript is to use the html attribute pattern (supported by most modern browsers). This works by setting the pattern of the second field to the value of the first field.
Unfortunately, you also need to escape the regex, for which no standard function exists.
<form>
<input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
<input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
</script>
JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output> element and an oninput form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):
<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
<input type="password" name="p1" value="" required />
<input type="password" name="p2" value="" required />
<output name="result"></output>
</form>
Not only HTML but a bit of JavaScript
HTML
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
<input type="password" placeholder="Password" id="password" required>
<input type="password" placeholder="Confirm Password" id="confirm_password" required>
<button type="submit" class="pure-button pure-button-primary">Confirm</button>
</fieldset>
</form>
JavaScript
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
confirm_password.setCustomValidity( password.value !=
confirm_password.value ? "Passwords Don't Match" : '');
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
CodePen Demo
As has been mentioned in other answers, there is no pure HTML way to do this.
If you are already using JQuery, then this should do what you need:
$(document).ready(function() {
$('#ourForm').submit(function(e){
var form = this;
e.preventDefault();
// Check Passwords are the same
if( $('#pass1').val()==$('#pass2').val() ) {
// Submit Form
alert('Passwords Match, submitting form');
form.submit();
} else {
// Complain bitterly
alert('Password Mismatch');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ourForm">
<input type="password" name="password" id="pass1" placeholder="Password" required>
<input type="password" name="password" id="pass2" placeholder="Repeat Password" required>
<input type="submit" value="Go">
</form>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
value={password}
onChange={(e) => { setPassword(e.target.value) }}
type="password" id='password' name="password" required minLength={3} maxLength={255} />
</div>
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
title='Passwords should be match'
pattern={`${password}`}
value={confirmPassword}
onChange={(e) => { setConfirmPassword(e.target.value) }}
type="password" id='confirmPassword' name="confirmPassword" required minLength={3} maxLength={255} />
</div>

Need help setting a minimum number of characters using JavaScript

I am trying to set a minimum of 5 characters for a password field and it is not working. Ever time I put in 0 or 1 characters it works but the challenge fails to work when entering 2 to 5 characters. Can someone take a look at what I have and tell me where I am going wrong?
<fieldset>
<legend>Password</legend>
<label>Create Password</label>
<input type="password" name="password" id"password"><br /><br />
<label>Confirm Password</label>
<input type="password" name="confirmPassword" id="confirmPassword">
</fieldset><br />
if (document.sample.password.value <=5) {
alert("Password must contain 5 characters.");
document.sample.password.select();
document.sample.password.style.backgroundColor="yellow";
return true; // leave now
}
Change it to:
<fieldset>
<legend>Password</legend>
<label>Create Password</label>
<input type="password" name="password" id="password"><br /><br />
<label>Confirm Password</label>
<input type="password" name="confirmPassword" id="confirmPassword">
</fieldset><br />
if (document.getElementById('password').length<=5) {
alert("Password must contain 5 characters.");
document.getElementById('password').select();
document.getElementById('password').style.backgroundColor="yellow";
return true; // leave now
}
Note the added = in the HTML for id"password"

equalTo validation with jQuery Validate

Below is my form which has password and confirm password field
<div class="form-group">
<label class="control-label">password</label>
<input type="text" class="form-control" name="password"
data-validate="minlength[8]"
data-message-required="email is required" placeholder="password">
</div>
<div class="form-group">
<label class="control-label">confirm password</label>
<input type="text" class="form-control" name="password_confirm"
data-validate="minlength[8],equalTo[password]"
data-message-required="email is required" placeholder="confirm password">
</div>
Below is my part of validation field.
if (params = rule.match(/(\w+)\[(.*?)\]/i)) {
if ($.inArray(params[1], ['minlength', 'equalTo']) != -1) {
opts['rules'][name][params[1]] = params[2];
message = $field.data('message-' + params[1]);
if (message) {
opts['messages'][name][params[1]] = message;
}
}
}
The minlength[8] seems to work perfectly, but when i try to match my password with confirm password its not working. I tried passing the name attribute in three ways, but none of them work.
equalTo[password]
equalTo["password"]
equalTo["#password"]
Also can anyone tell me what does this regular expression do /(\w+)\[(.*?)\]/i)
The parameter inside equalTo["#password"] is #password.
#password is a jQuery selector that matches an element with id="password". However, I don't see a id attribute on your password field. Try adding one...
<input type="text" class="form-control" id="password" name="password" ....
Quote OP:
"Also can anyone tell me what does this regular expression do /(\w+)\[(.*?)\]/i"
See: http://regexr.com/39d43

Categories

Resources