Client side input validation via Bootstrap and jQuery - javascript

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>

Related

Comma separated step for float number input

I want to comma seperated value for my input box. For Example 2100000.90 will be 2,100,000.90. What I achieved is 2100000.90 to 2,100,000 from some Solution in Stack overflow
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>
And My Javascript is
document.getElementById('salary').addEventListener('input', event =>
event.target.value = (parseInt(event.target.value.replace(/[^\d]+/gi, '')) || 0).toLocaleString('en-US')
);
I want both comma separated and value after point.
Thanks in advance
Your logic is defeated by its own.
Here is what you are currently doing:
ask the user to input a series of digits and only digits
parse the input into an integer
format the integer in the en-US locale
what will happen when the user tries to input a decimal point?
It will automatically be removed by the regex replace.
What you need to do is the following:
Allow the user to input digits and decimal points
That will mess up if the user types more than one decimal point, but that can be detected and dealt with later
Try to detect if the input is a valid number or not
if not, then provide a negative feedback to the user
if yes, then provide a positive feedback
most important: the process of converting text to number will get rid of the decimal point if it is the last character in the input box. The user will not see the dot since the conversion from text to number will see that it is the last thing and it's not affecting the number, so it is removed, and the user doesn't know why.
Therefor, it is essential to add the "dot" back if it is the last thing typed by the user.
document.getElementById('salary').addEventListener('input', event => {
event.preventDefault();
// allow only digits and dots
let text = event.target.value.replace(/[^\d\.]/gi, '');
// check if last character is a dot
let lastCharIsAdot = text.substr(text.length - 1, 1) === ".";
// try to check if input text is a valid number
if (isNaN(text)) {
// if not, then give feedback to the user
event.target.classList.remove('valid');
event.target.classList.add('invalid');
} else {
// if yes, then give positive feedback
event.target.classList.remove('invalid');
event.target.classList.add('valid');
// format number
event.target.value = Number(text).toLocaleString("en-US");
// this will remove the dot if it is the last thing input
// therefor, we need to put it back
if (lastCharIsAdot) event.target.value += ".";
}
});
.valid {
background-color: lightgreen;
color: darkgreen;
}
.invalid {
background-color: pink;
color: maroon;
}
<div class="input">
<label for="salary">Salary</label>
<input class='inp_cont' id="salary" name="salary" placeholder="Enter your salary" required="" type="text">
</div>
You can try this
parseInt(number, 10).toLocaleString()
here is also the link from mozilla docs about Number.prototype.toLocaleString() method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
This function help you :
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
Output :
numberWithCommas(88888888.88)); // 88,888,888.88

Add controls for minimum password length and complexity

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>

how to use regexp to validate form input javascript

I'm beginner at using JavaScript, and I have read documentation of RegExp and went trough couple of examples but I can't to figure it out how to use it properly.
I have a form which contains 5 input fields. I need to use RegExp to validate user input into form. The forbidden values are
( ) { } ' ! # “ \ /
Other characters are allowed but before submitting a form all input field must be entered (no blank/empty fields are allowed).
Input field id="unos_naziv_proizvoda" must contain at least 5 characters and start with capital letter.
Input field id="unos_opis_proizvoda" must contain at least 3 sentences. Sentence starts with a capital letter and end with a dot.
Input field id="unos_datum_proizvodnje" which is date of manufacturing must be in form of dd.mm.yyyy, can't be in the future (must be lower or same as today) and must be type text
Here is HTML code:
<form id="forma_prijava" class="forma_novi_proizvod" action="http://barka.foi.hr/WebDiP/2016/materijali/zadace/ispis_forme.php" method="POST">
<label for="unos_naziv_proizvoda">Naziv proizvoda</label>
<input type="text" name="naziv_proizvoda[15]" id="unos_naziv_proizvoda" placeholder="Unesite naziv proizvoda" maxlength="15">
<label for="unos_opis_proizvoda">Opis proizvoda</label>
<textarea name="opis_proizvoda" id="unos_opis_proizvoda" placeholder="Ovdje unesite opis proizvoda" rows="50" cols="100"></textarea>
<label for="unos_datum_proizvodnje">Datum proizvodnje</label>
<input type="date" name="datum_proizvodnje" id="unos_datum_proizvodnje">
<label for="unos_vrijeme_proizvodnje">Vrijeme proizvodnje</label>
<input type="time" name="vrijeme_proizvodnje" id="unos_vrijeme_proizvodnje">
<label for="unos_kolicina_proizvodnje">Količina proizvodnje</label>
<input type="number" name="kolicina_proizvodnje" id="unos_kolicina_proizvodnje" placeholder="Unesite količinu proizvodnje" min="1">
<button type="Submit" value="Submit">Dodaj proizvod</button>
<button type="Reset" value="Reset">Poništi unos</button>
</form>
Here is js code:
window.onload = function(){
var provjeri = function(){
var re = new RegExp(/[^(){}'!#"\/]/, g);
var uzorak = document.getElementById("forma_prijava"); //id of a form //
var ok = re.test(uzorak.value);
if(!ok){
alert("Niste unijeli valjani tekst"); //alert message if it's not valid input //
return false;
}
else{
alert("OK"); // message if it's valid input //
return true;
}
};
document.getElementById("forma_prijava").addEventListener("oninput", provjeri);
};
I don't know should I use it on a whole form as one unit or on each input field separately because I have different types of input fields (two are text and others are date, time and number). If someone could provide more understandable explanation when providing an example I would appreciate that. :)
Just to point it out once again, I strictly must use RegExp (pure JavaScript), no other libraries or frameworks do not come in mind!
Thank you in advance!
You can use property pattern of the input Tag
<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">

jQuery Click Function, input value length and pattern

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.

Password box - get value from input field with javascript

Does anybody know how to make a password box like this image?
This password box will be the first page of the site/mobile. The user have to insert 4 numbers (1 - 2 - 3 - 4). If they dont type 1 -2 - 3 - 4 as their password, they will get a message box saying "wrong password". If they type correct they will be sent to the next page.
Appreciate help!
Here a working sample
var password = [1,2,3,4];
var pwdInputs = $("#pwdContainer input");
var inputs = pwdInputs.toArray();
pwdInputs.keyup(function(){
if (this.value.length == this.maxLength) {
if(inputs.indexOf(this) == inputs.length-1){
testPassword();
} else {
$(this).next('input').focus();
}
}
});
function testPassword(){
var valid = true;
for(var i=0; i<inputs.length; i++){
if(password[i] != inputs[i].value){
valid = false;
break;
}
}
if(valid){
console.log("Correct Password!");
window.location.href = 'http://www.google.com';
}else{
console.log("Wrong Password!");
}
}
div.box-big {
background-color: grey;
margin: auto;
display:inline-block;
padding: 10px;
padding-top: 20px;
}
input.box-text {
width: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pwdContainer" class="box-big" >
<input type="text" maxlength="1" class="box-text" >
<input type="text" maxlength="1" class="box-text">
<input type="text" maxlength="1" class="box-text">
<input type="text" maxlength="1" class="box-text">
</div>
As per your comment, in the picture provided you seem to want to provide the user with 4 boxes, and in it, they would then type their password.
In this case, I do not think that you need regular expressions at all. What you need to do, in my opinion, is the following:
Create the 4 password field text boxes.
In the section where you check the password, simply check that the first box has a value of 1 stored in it, the second box has 2, the third has 3 and the fourth has 4.
Since you are looking for specific, entire string values, as opposed to patterns, regular expressions are not needed.
You probably want a regular expression (regex), which can be used to validate your input.
The regex string would look something like this: \d{4} or [0-9]{4}, which is basically saying match all digits (`\d' or numbers from 0-9) four times strictly, so only four digits exactly would be valid
<input type="password" pattern="[0-9]{4}" id="passcode" required onkeyup="checkIfValid()">
<p id="isValid"></p>

Categories