can someone tell me how to add controls for minimum password length and complexity
to my website
this is the database
CREATE TABLE Users(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
username VARCHAR(50) NOT NULL,
password VARCHAR(10) NOT NULL,
birthday DATE
);
CREATE TABLE dreams(
dream_id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(dream_id),
content text NOT NULL,
user_id INT,
FOREIGN KEY(user_id) REFERENCES Users(id)
);
I want when the users sign up and they try to create their passwords they get a message tell them that its too weak or that it has to be consisting of letters&numbers ..etc
is there something I can do through the database?
if its somewhere else please help I'm a beginner
I use nodejs-html-CSS-JavaScript
thank you.
You can use jquery.validate in your javascript code,
<script>
$("#form1").validate({
rules:{
password:{
required:true,
minlength:8
}
},
messages:{
password:{
required:"Password is required",
minlength:"Passowrd must be atleast 8 characters long"
}
}
});
</script>
password is the name attribute in your input field, and for picture in database you can use varbinary(max)
Firstly, you should set up validation to work from both the server-side and the client-side. Client-side, mostly for user experience, as a dev-savvy person can always circumvent anything in the browser. However, per your statement, you would like a nice user message and displaying that, no matter what is client-side, and this will help your users know better how to use your form. Server-side validation should also be in place to prevent bad data from being saved in your database.
In short, you will need them to work hand-in-hand. You don't need any sort of special js library for most basic validation. HTML5 will give you what you need to display many requirements without having extra javascript. However, using some kind of javascript is necessary if you don't like how HTML5 validation looks. But, I would always start by using it, because it will help your application meet accessibility standards easier and from there, you can iterate to make it look nicer by adding fancier javascript-based things on top of it.
The snip will have a warning overlay that won't happen on your website. See (https://www.w3schools.com/tags/att_input_pattern.asp) for more information and this same example.
<form action="">
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters">
<input type="submit">
</form>
Now on your backend, you should create a function in the code that processes the form to recheck the validation before saving it to the database along with your other DB rules. If this validation fails because somehow the user or some bug allowed the validation to be circumvented, you would send back a failure message in the form response that the front-end would catch and display after a failed attempt to save to the database. Answering how exactly to go about that would require much more information on how your app is setup.
You could also create a table in the database to store your validation rules and could pass those rules to the front-end via some kind of API so the frontend and backend functions can share the same rules and not have to hardcode the same regular expressions or whatever rule you are dealing with. In other words, a single point of truth for both validations -- the user experience check and the data integrity check.
I'm Using Validation Password for detected Weak or Strong Password:
I have 2 example:
This is Pure Javascript
var code = document.getElementById("password");
var strengthbar = document.getElementById("meter");
var display = document.getElementsByClassName("textbox")[0];
code.addEventListener("keyup", function() {
checkpassword(code.value);
});
function checkpassword(password) {
var strength = 0;
if (password.match(/[a-z]+/)) {
strength += 1;
}
if (password.match(/[A-Z]+/)) {
strength += 1;
}
if (password.match(/[0-9]+/)) {
strength += 1;
}
if (password.match(/[$##&!]+/)) {
strength += 1;
}
if (password.length < 6) {
display.innerHTML = "minimum number of characters is 6";
}
if (password.length > 12) {
display.innerHTML = "maximum number of characters is 12";
}
switch (strength) {
case 0:
strengthbar.value = 0;
break;
case 1:
strengthbar.value = 25;
break;
case 2:
strengthbar.value = 50;
break;
case 3:
strengthbar.value = 75;
break;
case 4:
strengthbar.value = 100;
break;
}
}
<body>
<form class="center-block">
<input type="text" id="password" autocomplete="off" class="form-control input-lg">
<progress max="100" value="0" id="meter"></progress>
</form>
<div class="textbox text-center"> password </div>
</body>
This is jQuery
function ValidatePassword() {
/*Array of rules and the information target*/
var rules = [{
Pattern: "[A-Z]",
Target: "UpperCase"
},
{
Pattern: "[a-z]",
Target: "LowerCase"
},
{
Pattern: "[0-9]",
Target: "Numbers"
},
{
Pattern: "[!###$%^&*]",
Target: "Symbols"
}
];
//Just grab the password once
var password = $(this).val();
/*Length Check, add and remove class could be chained*/
/*I've left them seperate here so you can see what is going on */
/*Note the Ternary operators ? : to select the classes*/
$("#Length").removeClass(password.length > 6 ? "glyphicon-remove" : "glyphicon-ok");
$("#Length").addClass(password.length > 6 ? "glyphicon-ok" : "glyphicon-remove");
/*Iterate our remaining rules. The logic is the same as for Length*/
for (var i = 0; i < rules.length; i++) {
$("#" + rules[i].Target).removeClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-remove" : "glyphicon-ok");
$("#" + rules[i].Target).addClass(new RegExp(rules[i].Pattern).test(password) ? "glyphicon-ok" : "glyphicon-remove");
}
}
/*Bind our event to key up for the field. It doesn't matter if it's delete or not*/
$(document).ready(function() {
$("#NewPassword").on('keyup', ValidatePassword)
});
.glyphicon-remove {
color: red;
}
.glyphicon-ok {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group has-feedback">
<input class="form-control" id="NewPassword" placeholder="New Password" type="password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div id="Length" class="input glyphicon-remove">Must be at least 7 charcters</div>
<div id="UpperCase" class="glyphicon glyphicon-remove">Must have atleast 1 upper case character</div>
<div id="LowerCase" class="glyphicon glyphicon-remove">Must have atleast 1 lower case character</div>
<div id="Numbers" class="glyphicon glyphicon-remove">Must have atleast 1 numeric character</div>
<div id="Symbols" class="glyphicon glyphicon-remove">Must have atleast 1 special character</div>
Related
I am kind of stuck, with this I don't even know where to start but
I need to mark the first input as green on the correct password, red if the password does not meet the requirements
Requirements:
Passwords must be at least 10 characters long and have lowercase and uppercase letters
Passwords less than 15 characters must have a number and a special character
Marking the second input outline as green if it matches the first input and the password is correct, red otherwise.
Any help would be very appriciated
<div class="form-group">
<label for="newPasswordTextBox">Password</label>
<input type="password" id="newPasswordTextBox" class="form-control" name="newPassword"
placeholder="New Password" autocomplete="off">
</div>
<div class="form-group">
<label for="confirmNewPasswordTextBox">Confirm Password</label>
<input type="password" id="confirmNewPasswordTextBox" class="form-control"
name="confirmNewPassword" placeholder="Confirm New Password" autocomplete="off">
</div>
<div class="small">
<ul>
<li>Passwords must be at least 10 characters long and have a lowercase and
uppercase letters</li>
<li>Passwords less than 15 characters must have a number and a special
character</li>
</ul>
</div>
You could try using javascript to collect both inputs document.getElementById("newPasswordTextBox") and document.getElementById("confirmNewPasswordTextBox") and then you can take the .value attributes from the input boxes to check the input against if conditionals with your specified requirements. eg.
let newPass=document.getElementById("newPasswordTextBox");
newPass.addEventListener("keyup",function(evt){
let val=newPass.value;
//check requirements here
});
or in jquery
$("#newPasswordTextBox").on("keyup", function(evt){
let val=$("#newPasswordTextBox").val(); //get the value using jquery
//check requirements here
});
Next, use if conditionals by //check requirements here to get your functionality. You can use val.length to get the length of the string obtained from the textbox, then just compare this to the size you want(10). Repeat the aforementioned for 15 but just add the extra requirements of checking for numbers and special characters(see regular expressions in javascript). For validating that passwords match just grab both values and use "===" to determine if they are equal. You can also change the input boxes' outline colours using the border property as follows:
$("#newPasswordTextBox").css({"border-color":"green"});//Use the appropriate id and colour for the box you wish to change
Addition(correcting the authors code post):
I've managed to capture most of what I believe you'd want here and corrected some of your code by changing the wrong variables that were called and changed to the proper regex code.
$("#newPasswordTextBox").on("keyup", function () {
let pass = $("#newPasswordTextBox").val();
if ((pass.length >=10) && (pass.length < 15)) {
var regex = /^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[ `!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~])/;
if(!pass.match(regex)){
$("#newPasswordTextBox").css({ "border-color": "red"});
}
else{
$("#newPasswordTextBox").css({ "border-color": "green" });
}
} else if (pass.length>=15){
$("#newPasswordTextBox").css({ "border-color": "green","outline":"none" });
}else {
$("#newPasswordTextBox").css({ "border-color": "red","outline":"none" });
}
}
);
$("#confirmNewPasswordTextBox").on("keyup", function () {
let pass = $("#confirmNewPasswordTextBox").val();
let confpass = $("#newPasswordTextBox").val();
if (pass === confpass) {
$("#confirmNewPasswordTextBox").css({ "border-color": "green","outline":"none" })
} else {
$("#confirmNewPasswordTextBox").css({ "border-color": "red","outline":"none" });
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<body>
<input type="text" id="newPasswordTextBox" placeholder="new">
<input type="text" id="confirmNewPasswordTextBox" placeholder="re-enter">
</body>
I'm working on an assignment and need to validate multiple inputs. I have created multiple functions and am having trouble calling each one. The first one is the only one that will call. The other two will just hang and do nothing.
If I do a single function call for oninput at the form tag it works. Just that it automatically calls the function and all validations. This causes all the prompts to come out at the same time which I don't want. This is why the oninput call is being done at the input tag.
HTML:
<div id="nameValidate"></div>
<label for="name">Name:</label>
<input type="text" id="nameID"
oninput="nameValidation()"/> <br />
<div id="emailValidate"></div>
<label for="email">Email:</label>
<input type="text" id="emailID"
oninput="emailValidation()"/> <br />
<div id="phoneValidate"></div>
<label for="phone">Phone Number:</label>
<input type="number" id="phoneID"
oninput="phoneValidation()"/>
Javascript
function nameValidation() {
var name = document.getElementById("nameID").value;
if (name.length < 3) {
document.getElementById("nameValidate").innerText = "Please
enter your full name.";
}
else if (name.length > 3) {
document.getElementById("nameValidate").innerText = "";
}
}
function emailValidation() {
var email = document.getElementById("emailID").value;
if (!email.match(".com") && email < 5) {
document.getElementById("emailValidate").innerText = "Please
enter your full email address.";
}
else {
document.getElementById("emailValidate").innerText = "";
}
}
function phoneValidation() {
var phone = document.getelementbyid("phoneID").value;
if (phone == "" || phone.length < 10) {
document.getelementbyid("phoneValidate").innertext = "please
enter your full phone number.";
}
else if () {
document.getelementbyid("phoneValidate").innertext = "";
}
}
Let's back up a minute and break some very bad habits that someone who doesn't know any better is teaching you.
Do not set up events using inline HTML event attributes (ie. onclick). This is a 25+ year old technique that persists today because people just copy/paste it and it seems to work in many cases. However, there are a number of very good reasons not to use this ancient technique that just will not die. Separate your JavaScript from your HTML and use modern, standards-based approaches to event handling with .addEventListener().
You've also mis-capitalized .getElementById() when you were getting the phone data and this would cause an error in your code that would prevent it from continuing. Always work with your developer tools (F12) open and the Console tab showing as this is where error messages will appear.
Next, only query the DOM once for elements that you'll need over and over. This means remove all the document.getElementById() lines from inside the functions and move them so they just get executed only once.
And, don't make references to properties of DOM elements, make the references to the element itself. This way, you scan the document just once to get the element reference, but then you can get any property you like when you need it without having to scan the document for the same element again.
Next, don't use .innerText as it is non-standard. Use .textContent instead.
And, don't use self-terminating tag syntax (ie.<br />, <input />). Here's why.
So, here's what your code should look like:
// Get references to the elements you'll be working with just once
var userName = document.getElementById("nameID");
var nameValidate = document.getElementById("nameValidate");
var email = document.getElementById("emailID");
var emailValidate = document.getElementById("emailValidate");
var phone = document.getElementById("phoneID");
var phoneValidate = document.getElementById("phoneValidate");
// Set up your event handlers in JavaScript, not HTML
userName.addEventListener("input", nameValidation);
email.addEventListener("input", emailValidation);
phone.addEventListener("input", phoneValidation);
function nameValidation() {
if (this.value.length < 3) {
nameValidate.textContent = "Please enter your full name.";
} else {
nameValidate.textContent = "";
}
}
function emailValidation() {
// Check the last 4 characters of the input
if ((this.value.substr(this.value.length - 4) !== ".com") && email.value.length < 5) {
emailValidate.textContent = "Please enter your full email address.";
} else {
emailValidate.textContent = "";
}
}
function phoneValidation() {
if (phone.value == "" || phone.value.length < 10) {
phoneValidate.textContent = "please enter your full phone number.";
} else {
phoneValidate.textContent = "";
}
}
<div id="nameValidate"></div>
<label for="name">Name:</label>
<input type="text" id="nameID"> <br>
<div id="emailValidate"></div>
<label for="email">Email:</label>
<input type="text" id="emailID"> <br>
<div id="phoneValidate"></div>
<label for="phone">Phone Number:</label>
<input type="number" id="phoneID">
Finally, as a professional technology trainer for over 25+ years, I would strongly advise you to inform whoever is teaching you these outdated techniques that they are doing you and anyone else they are teaching a disservice. Modern web development is hard-enough without having to unlearn bad habits brought on by those who don't know any better.
Firstly, your elseif has brackets but the condition is empty. Check your console, it should be showing a syntax error because:
} else if () {
document.getelementbyid("phoneValidate").innertext = "";
}
is not valid syntax. Turn it into an else.
Secondly, the function:
document.getelementbyid("phoneValidate").innertext = "";
does not exist on document, however, getElementById does.
Finally, ensure that you use the console to help you debug your code.
I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.
Hi I have a password checker but I don't know what code I should use for my program. I need my program to check against the rules but I don't know how to do that. I was hoping someone would know how to do that or at least help me in doing so.
These are the specks of my program.
The user types in their desired password, and based on a series of checks, the system tells them if their password is a strong password or not.
For a password to be considered strong, it must pass the following tests:
A password must contain at least 1 capital letter
A password must contain at least 1 lower-case letter
A password must contain at least 1 number
A password must contain at least 1 of the following chars: ! # # $ % ^ &
A password must be at least 8 chars long
As the user types, they should be given feedback on the strength of their password.
You will need to check each letter so see if the password matches these rules.
This is my HTML.
<div style="text-align: center;" style="font-weight:bold;">
<h1> Password Strength Checker</h1>
<br/>
The most secure passwords will have a very strong rating.
<br/>
The ratings scale range from: Weak (0), Good (25) , Medium (50), Strong (75) and Very Strong (100).
<br/>
<br/>
RULES:
<br/>
1. Your password must contain at least 1 number.
<br/>
2. Your password must be at least 8 characters long.
<br/>
3. Your password must contain at least 1 capital letter.
<br/>
4. Your password must contain at least 1 lowercase letter.
<br/>
5. Your password must contain at least 1 of the following characters:
<br/>! # + # $ % ^ & * , ? _ ~ - ( )
<br/>
Spaces are not allowed.
<br/>
<br/>
<input type="text" id="password" size="30" name="password" autocomplete="off" onkeydown="passwordStrength(this.value);"><span id="passwordStrength" class="strength0"><span id = "passwordDescription"><br/>
Please Enter Password <br/>
This is my JavaScript.
function passwordStrength(password) {
var rating = [
0, "<font color='black'> Weak </font>",
25, "<font color='red'> Good </font>",
50, "<font color='yellow'> Medium </font>",
75, "<font color='blue'> Strong </font>",
100, "<font color='green'> Very Strong </font>"];
var score = 0;
var pass = "";
if (password.length > 8) {
score += 25;
}
if ((password.match(/[a-z]/)) && (password.match(/[A-Z]/))) {
score += 25
}
if (password.match(/.[,!,#,#,$,%,^,&,*,?,_,~,-,(,)]/)) {
score += 25;
}
if (password.match(/[0-9]/)) {
score += 25
}
if (password.match(/d+/)) {
score += 10;}
for (var i = rating.length - 1; i >= 0; i -= 1) {
if (score >= rating[i]) {
pass = rating[i +1];
break;
}
}
document.getElementById("passwordDescription").innerHTML = "<b>" + pass + score + "</font></b>"
document.getElementById("passwordStrength").className = "strength" + score;
}
This is my jsfiddle. http://jsfiddle.net/jYcBT/138/
Not sure what is your question?
However, I just fixed your special characters regular expression
password.match(/[\!\#\#\$\%\^\&\*\?\_\~\-\(\)]+/)
Remove the extra 10 points that you had, not sure why you added this?
change the event from onkeydown to onchange.
It works fine as far as i understand your flow.
http://jsfiddle.net/jYcBT/140/
Hi I have looked around online and I am aware that similar questions have been asked, however, I am unable to find a suitable solution to my problem. I need this code to be password validated, the problem is that I'm not directly working with an <input> field therefore I've been unable to figure out how to implement JS.
Here is the HTML (it's implemented using ruby-on-rails, this is all the 'HTML' side that I can see (full code in fiddle below))
<form accept-charset='utf-8' method='post' name="form" action='register' class="registerform" onsubmit="return validate_form()">
<h3 class="registernospace">Contact Information</h3>
<table>
<tbody>
<tr><td class="registerrowspace" colspan="2">The Password must be at least 6 characters long and should contain a mixture of lower case letters, upper case letters, and numbers.<br />The Confirm Password must match the Password.</td></tr>
<tr><th class="registerrowspace">Password</th><td id="password1" class="registerrowspace"><%= field('password') %></td></tr>
<tr><th class="registerrowspace">Confirm Password</th><td id="password2" class="registerrowspace"><%= field('password') %></td></tr>
<tr><th class="registerrowspace">Date of Birth</th><td class="registerrowspace">
</tbody>
</table>
<% end %>
<input type='hidden' name='register_submitted' value='yes'/>
<p><input type='submit' class="button" value='Register Now' /></p>
</form>
And I have tried Implementing some JS (but being unfamiliar with the language I haven't been able to get it working, but I was trying to do something like this:
<script type="text/javascript">
function validate_form()
{
var passw = document.getElementById('password1').value;
if(passw.value.length < 6 ) {
alert("Error: Password must contain at least six characters!");
form.password.focus();
return false;
}
return true;
}
</script>
So I was hoping it validates and raises a message if its blank, if its < 6 chars and if it does not include a Uppercase and a number. Although I'm aware I haven't introduced the latter in the code, I couldn't even get the <6 to work.
Also I have other validations (which were built by default which work) and you can see the full:
Fiddle code
Live Website
if(passw.value.length < 6 ) {
should be
if(passw.length < 6 ) {
because you already get its value
var passw = document.getElementById('password1').value;
UPDATE:
password1 is <td> id not of password feild
i just check your link, it was giving error passw is undefined in console, you password field id is password-input-0, so use
var passw = document.getElementById('password-input-0').value;
^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$
---
^.* : Start
(?=.{6,}) : Length
(?=.*[a-zA-Z]) : Letters
(?=.*\d) : Digits
(?=.*[!#$%&? "]) : Special characters
.*$ : End
function validatePassword() {
var newPassword = document.getElementById('changePasswordForm').newPassword.value;
var regularExpression = ^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$/;
alert(newPassword);
if(!regularExpression.test(newPassword)) {
alert("password should contain atleast one number and one special character");
return false;
}
}
Instead of using if(passw.value.length < 6 ) use if(passw.length < 6 ) you have already value of password you only need to check for size.
Also, Your textfield name is wrong. 'Password1' is td name not password textfield. Please check and correct.
if(passw.length < 5 ) //here should be 5
Page refreshes when you click the button :you don't call e.preventDefault(); I think you should listen 'submit' event. In the 'listen' function you may validate the length of the input and prevent it's default behavior.