Javascript, validation of password with bootstrap - javascript

i'm trying to learn Javascript and some basic HTML with bootstrap v5.
I created a Sign-in form and now i'm try to do some validation for the required field.
I follow the Bootstrap documentations and i managed to get validation for all my input field except for the password, i want to verify if the password are the same or if they are empty field...but i'm stuck.. not familiar with javascript.
my attempt in javascript:
let forms = document.querySelectorAll(".needs-validations");
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
Array.prototype.slice.call(forms).forEach( function (form){
form.addEventListener("submit",function (ev) {
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.className = 'form-control is-invalid'
pass2.className = 'form-control is-invalid'
}
if (!form.checkValidity()){
ev.preventDefault()
ev.stopPropagation()
}
form.classList.add("was-validated")
})
})
but here the result:
As you can see password is always valid and i don't understand why.
my html:
<body class="body">
<div class="center">
<h4 class="title">Sign Up New User</h4>
<form name="signin-form" method="post" class="needs-validations" novalidate id="forms">
<div class="container">
<div class="row mt-3">
<div class="col">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" required>
<div class="invalid-feedback">
Name can't be empty
</div>
</div>
<div class="col">
<label for="surname" class="form-label">Surname</label>
<input type="text" class="form-control" id="surname" placeholder="Surname" required>
<div class="invalid-feedback">
Surname can't be empty
</div>
</div>
</div>
<div class="row mt-3">
<div class="col">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" required>
<div class="invalid-feedback">
invalid email
</div>
</div>
<div class="col-4 text-end">
<label for="email" class="form-label">Role</label>
<select class="form-select" id="validationCustom04" required>
<option selected disabled value="">Choose...</option>
<option>Captain</option>
<option>First Officer</option>
</select>
<div class="invalid-feedback">
Please select role
</div>
</div>
</div>
<div class="row mt-3 ">
<div class="col">
<label for="password1" class="form-label ">Password</label>
<input type="password" class="form-control" id="password1" placeholder="Password">
</div>
<div class="col">
<label for="password2" class="form-label ">Confirm Password</label>
<input type="password" class="form-control" id="password2" placeholder="Password">
<div class="invalid-feedback">
Password not match
</div>
</div>
</div>
<div class="row-cols-2 mt-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</div>
<script src="/validation.js"></script>
<script src="/js/bootstrap.bundle.min.js" ></script>
</body>

What I don't understand is, that your password fields seem to be having a valid class in your posted screenshot. But I can't find it anywhere in your code (neither HTML nor JS).
I'd do it like this:
(Note: I didn't test this code, but it should work. If it works and you want to learn from it, I recommend to read through it step by step and apply it to your logic instead of just copy pasta.)
let form = document.querySelector("form.needs-validations");
// or, to be more specific:
// let form = document.querySelector("form[name='signing-form']")
form.addEventListener("submit",function (ev) {
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.classList.add('is-invalid');
pass2.classList.add('is-invalid');
}
if (!form.checkValidity()){
ev.preventDefault();
ev.stopPropagation();
}
form.classList.add("was-validated");
})
Note: the functionality to validate the content of your password-fields will only be triggered once you hit the submit button.

Related

How to compare new password and confirm password using JavaScript Angular

I need to compare below new password field and confirm password field. This is the form
<form novalidate (ngSubmit)="changepasswordform.form.valid && changePassword(this.changepassword, changepasswordform)"
#changepasswordform="ngForm">
<div class="form-group row">
<label for="email5" class="col-sm-5 col-md-5 col-form-label">New Password</label>
<div class="col-sm-7 col-md-7">
<input type="password" class="form-control" pattern="^(?=.*[A-Za-z])(?=.*\d).{8,}$" required
[class.is-invalid]="newpassword.invalid && newpassword.touched" name="newpasswords"
#newpassword="ngModel" [(ngModel)]="changepassword.newPassword"
placeholder="New Password">
<div [class.d-none]="newpassword.valid || newpassword.untouched">
<small class=" text-danger" *ngIf="newpassword.errors?.required">Password is
required</small>
<small *ngIf="newpassword.hasError('pattern')" class=" text-danger">
Password should be 8 characters, at least one
letter and one number</small>
</div>
</div>
</div>
<div class="form-group row">
<label for="email5" class="col-sm-5 col-md-5 col-form-label">Confirm Password</label>
<div class="col-sm-7 col-md-7">
<input type="password" class="form-control"
[class.is-invalid]="repassword.invalid && repassword.touched" name="repassword"
#repassword="ngModel" placeholder="Confirm Password" compare="newpassword"
[(ngModel)]="changepassword.repassword" required>
<div [class.d-none]="repassword.valid || repassword.untouched">
<small *ngIf="repassword.errors?.required" class="text-danger">Confirm password is
required</small>
</div>
<div class="text-danger"
*ngIf="repassword.invalid && (repassword.dirty || repassword.touched)">
<small class="login-val" *ngIf="repassword.errors['compare']"> Confirm password do not
match</small>
</div>
</div>
</div>
</form>
When user type the text box, validation should be check. Do you know how to do this. I need to do this without any library.
Since you are not using reactive forms, you can directly perform a comparison between the models newPassword and repassword to set the error message.
Please refer following stackblitz.
Code: here
Output: here

Phone Number Regex Validation error while showing/hiding Elements

I am working on a form where I am showing a div when a user submits the form and it checks if all the fields values are not blank. I have achieved that part and it is working fine.
Now the problem is when I am validating the phone number using regex, it is showing error but still displays the div and form is also submitted successfully. It should not get submit till the user enters a correct phone number, it gives an error and still, the form gets submitted. I know the error is there but I am not understanding where I am wrong. Please guide me.
function mySub() {
const user = document.getElementById('pmname').value.trim();
const uemail = document.getElementById('pmemail').value.trim();
const uphone = document.getElementById('pmphone').value.trim();
const uregx = /^[0-9]{10}$/;
const upmmb = uregx.test(uphone);
if (user == "" || uemail == "" || uphone == "" || upmmb == "") {
document.getElementById('agy').style.display = 'none';
alert("Enter Valid Mobile Number");
document.getElementById('pmphone').focus();
} else {
document.getElementById('agy').style.display = 'block';
}
}
#agy {
display: none;
}
<form method="post" action="#">
<div id="agy">
<div class="agent-details">
<div class="d-flex align-items-center">
<div class="agent-image">
<img class="rounded" src="#" alt="Jazz" width="70" height="70" />
</div>
<ul class="agent-information list-unstyled">
<li class="agent-name"><i class="houzez-icon icon-single-neutral mr-1"></i> Jazz</li>
<li class="agent-link">View Listings</li>
</ul>
</div>
</div>
</div>
<div class="form-group">
<input class="form-control" name="name" id="pmname" value="" type="text" placeholder="Name" />
</div>
<div class="form-group">
<input class="form-control" name="mobile" id="pmphone" value="" type="text" placeholder="Phone" />
</div>
<div class="form-group">
<input class="form-control" name="email" id="pmemail" value="" type="email" placeholder="Email" />
</div>
<div class="form-group form-group-textarea">
<textarea class="form-control hz-form-message" name="message" rows="4" placeholder="Message">Hello, I am interested in ...</textarea>
</div>
<div class="form-group">
<label class="control control--checkbox m-0 hz-terms-of-use">
<input type="checkbox" id="ppa" name="privacy_policy" checked="" />By submitting this form I agree to <a target="_blank" href="https://propertymakkerz.com/pm/property/sai-ashishkaranjadepanvel/">Terms of Use</a>
<span class="control__indicator"></span>
</label>
</div>
<div class="form_messages"></div>
<button type="button" class="houzez_agent_property_form btn btn-secondary btn-full-width" onclick="mySub()"><span class="btn-loader houzez-loader-js"></span> Send Message</button>
</form>

Javascript doesnt seem to be attachet to my jsp

When i load login.jsp it doesn't alert if i dont input password or username
tried checking wether i correctly attached the file but it still doesnt work for me, what could be the reason?jsp just reacts the way it would react if i wouldn't use js at all
LoginPage.js
function check()
{
var username = document.form.username.value;
var password = document.form.password.value;
if (username==null || username=="")
{
alert("Username can't be blank");
return false;
}
else if(password==null||password=="")
{
alert("Password must be inserted ");
return false;
}
}
my jsp:
<body>
<div class="card-body">
<form method="get" action="LoginServlet" onsubmit="return check()">
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input id="username" type="text" class="form-control" placeholder="username" name="username">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input id="password" type="password" class="form-control" placeholder="password" name="password">
</div>
<div class="form-group">
<input id="login-button" type="submit" value="Login" class="btn float-right login_btn" >
</div>
</form>
</div>
<div class="card-footer">
<div class="d-flex justify-content-center links">
Don't have an account?Sign Up
</div>
</div>
</div>
</div>
</div>
<script src="LoginPage.js"></script>
</body>
</html>
any suggestions ?
firstly check the HTML syntax of your jsp, it seems that the html is broken because of the last three </div> because of the missing opening tags.
Then, you don't have by default a document.form property so you could get your username and password in the following way:
// or you can use document.getElementById('username')
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
here details about the querySelector function

Show add button only when the form is dirty

I have a form with email, password, and password again. I want to hide the add sign by default, and only show it if my form is dirty and password matches password again.
I can’t seem to get it to work.
<div ng-controller="MyCtrl">
Hello, {{name}}!
<form name="addUserForm">
<div class="form-row row">
<div class="col-xs-3 col-sm-3">
<input ng-model="newLogin.email" ng-blur="checkEmailRestriction(newLogin.email)" required type="text" class="form-control input-sm" placeholder="Email">
</div>
<div class="col-xs-3 col-sm-3">
<input ng-model="newLogin.password" required stopccp type="password" class="form-control input-sm" ng-change="checkPwdRestriction(newLogin.password)" placeholder="Password">
</div>
<div class="col-xs-3 col-sm-3">
<input stopccp ng-model="newLogin.passwordAgain" ng-change="checkPwdMatch(newLogin.password,newLogin.passwordAgain)" type="password" class="form-control input-sm" placeholder="Password Again">
</div>
<div class="col-xs-3 col-sm-3">
<a ng-click="storeLogin()" ng-if="newLogin.password === newLogin.passwordAgain && addUserForm.$dirty == false" class="btn btn-xs email-action"> add </a>
</div>
</div>
</form>
<hr>
<p>
object = ? {{newLogin}}
</p>
<p>
$dirty = ? {{addUserForm.$dirty}}
</p>
<p>
$valid = ? {{addUserForm.$valid}}
</p>
</div>
I’ve tried
http://jsfiddle.net/bheng/5pzL8gc3/
I hided your button with this :
ng-show="newLogin.password && newLogin.password == newLogin.passwordAgain && addUserForm.$dirty == true"
And it appears when I provide an email and passwords that match.

Onsubmit not working

I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?
First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.
First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>

Categories

Resources