How to compare passwords in Javascript - javascript

I have a registration page and I want to compare two passwords (input fields) to be equal before writing it to a websql database.
I cannot seem to get it to work.
Any ideas?
function addTodo() {
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) {
alert("Yours passwords do not match");
} else {
curatio.webdb.addTodo(todo.value);
todo.value = "";
alert("Your Registration was successfull");
setTimeout(function () {
window.location.href = "login.html";
}, 1000);
}
}
<div data-role="fieldcontain" >
<label for="todo">
Password
</label>
<input name="" id="todo" placeholder="" value="" type="password" required>
</div>
<div data-role="fieldcontain" >
<label for="todo2">
Retype your Password
</label>
<input name="" id="todo2" placeholder="" value="" type="password" required>
</div>

You're comparing the elements instead of their values.
var todo = document.getElementById("todo");
var todo2 = document.getElementById("todo2");
if(todo != todo2) { // Oops
todo and todo2 are 2 different <input> elements.
Try using .value:
if(todo.value !== todo2.value) {

You're comparing the actual elements, which will always be true (because they are both TextFields). Compair their values, like so:
var todo = document.getElementById("todo").value;
var todo2 = document.getElementById("todo2").value;
Either this or change
if(todo != todo2)
to
if(todo.value != todo2.value)

Another way is Object.is(password, confirm_password)

Related

HTML JS manual form validation not working

I'm trying to manually validate a form in HTML/CSS/JS. At the very basic level, I want to ensure that the user cannot input blank values for first name and last name. The problem is that whenever I try to change or update the inputs to what the user has written, it doesn't save. Everything remains "null". It's also extremely frustrating that in my JS code when I'm trying to use an IF statement to check if the first name has no value or is null, I get an immediate error message that "first" is null, because its null no matter what, if you input something or not, but it doesn't even complete it's job. I'm using the if statement to CHECK if its null, not for it to do something with it, so why is it having an issue simply following the code below it if the condition is true? I've sat on this for like an hour and its becoming unbearable. I'm new to JS and Im really not getting how something as simple as IF statements isn't working for me.
HTML form:
<form action="" method="get" id="my-form">
<h1>Contact Us</h1>
<div class="txtb">
<label>First Name :</label>
<input type="text" id = "firstname" placeholder="Enter Your First Name">
</div>
<div class="txtb">
<label>Last Name :</label>
<input type="text" id = "lastname" placeholder="Enter Your Last Name">
</div>
<div class="txtb">
<label>Email :</label>
<input type="email" id = "email" placeholder="Enter Your Email" required>
</div>
<div class="txtb">
<label>Date Visited :</label>
<input type="date" id = "date" required>
</div>
<div class="txtb">
<label>What did you think of it when you visited? :</label>
<textarea id = "msg" required></textarea>
</div>
<button type='submit'>Submit</button>
<!--onclick = form.submit()-->
</form>
</div>
<div id="error"></div>
New JS:
let first = document.getElementById("firstname").value;
let last = document.getElementById("lastname").value;
let email = document.getElementById("email").value;
let msg = document.getElementById("msg").value;
let date = document.getElementById("date").value;
let form = document.getElementById("my-form");
let errorEl= document.getElementById("error");
function formChanged() {
first = document.getElementById("firstname");
last = document.getElementById("lastname");
email = document.getElementById("email");
msg = document.getElementById("msg");
date = document.getElementById("date");
console.log(first,last,email,msg,date,form)
}
form.addEventListener('submit', (e) => {
let messages = []
console.log(first, last)
if (first === '' || first == null){
messages.push('First name is required')
}
if (last === '' || last == null){
messages.push('Last name is required')
}
if (messages.length>0){
e.preventDefault()
errorEl.innerText = messages.join(', ')
}
console.log(first, last)
})
//window.alert(messages)
If anyone knows a better way to do this manually also, it would be greatly appreciated if you could share it. At this point, everything works except the messages array remains the same, so I'm going to add something to remove the messages if first doesn't == null or ''
Edit :
You are doing first = document.getElementById("firstname").value; so it get by ID but you don't have any id.
For example, change
<input type="text" name = "firstname" placeholder="Enter Your First Name">
to
<input type="text" id="firstname" name="firstname" placeholder="Enter Your First Name">
Notice the id="firstname".
Original Answer :
Your function
function formChanged() {
first = document.getElementById("firstname").value;
last = document.getElementById("lastname").value;
email = document.getElementById("email").value;
msg = document.getElementById("msg").value;
date = document.getElementById("date").value;
console.log(first,last,email,msg,date,form)
}
Is setting first to document.getElementById("firstname").value; while you first initialized it to
let first = document.getElementById("firstname");.
Notice, that in your function you set it to the input's .value, not the input itself.
So if (first.value === '' || first.value == null) won't work because first is already equal to .value thus you are in fact doing document.getElementById("firstname").value.value which is undefined !
Try either :
to change formChanged variable initialisation to document.getElementById("firstname")
OR
change the if to if (first == '' || first== null)
Adding on to what Sorikairo said:
From this answer, add a return value to your onsubmit instead of preventDefault:
if (messages.length>0){
// e.preventDefault()
return false;
errorEl.innerText = messages.join(', ')
}
return true;
SOLVED:
If you run into this problem, check all of your .value lines, because doubling them up or not having enough was the main problem here. Everything was being checked against the wrong things. I also recommend console.log() ing everything you do like I did just for variable tracking.
Final JS:
let first = document.getElementById("firstname").value;
let last = document.getElementById("lastname").value;
let email = document.getElementById("email").value;
let msg = document.getElementById("msg").value;
let date = document.getElementById("date").value;
let form = document.getElementById("my-form");
let errorEl= document.getElementById("error");
function formChanged() {
first = document.getElementById("firstname").value;
last = document.getElementById("lastname").value;
email = document.getElementById("email").value;
msg = document.getElementById("msg").value;
date = document.getElementById("date").value;
form= document.getElementById("my-form");
errorEl = document.getElementById("error");
console.log(first,last,email,msg,date,form)
}
form.addEventListener('submit', (e) => {
formChanged()
errorEl.innerText = '';
var messages = []
if (first === '' || first == null){
messages.push('First name is required')
}
if (last === '' || last == null){
messages.push('Last name is required')
}
if (messages.length>0){
e.preventDefault()
errorEl.innerText = messages.join(', ')
}
console.log(first, last)
console.log(messages)
})
//window.alert(messages)
Final HTML:
<form action="" method="get" id="my-form">
<h1>Contact Us</h1>
<div class="txtb">
<label>First Name :</label>
<input type="text" id = "firstname" placeholder="Enter Your First Name">
</div>
<div class="txtb">
<label>Last Name :</label>
<input type="text" id = "lastname" placeholder="Enter Your Last Name">
</div>
<div class="txtb">
<label>Email :</label>
<input type="email" id = "email" placeholder="Enter Your Email" required>
</div>
<div class="txtb">
<label>Date Visited :</label>
<input type="date" id = "date" required>
</div>
<div class="txtb">
<label>What did you think of it when you visited? :</label>
<textarea id = "msg" required></textarea>
</div>
<button type='submit'>Submit</button>
<!--onclick = form.submit()-->
</form>
</div>
<div id="error"></div>

checking object for blank values and show errors

I am trying to figure out how I can check if any values in the object are blank, and then show the corresponding error.
The form inputs look like this:
<form role="form" action="home.php" class="addLaneForm" id="addLaneForm" name="addLaneForm">
<label for="addlanepartnercode">Partner Code</label><span id="addlanepartnercodeError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnercode" placeholder="Enter Partner Code" />
<label for="addlanepartnername">Partner Name</label><span id="addlanepartnernameError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnername" placeholder="Enter Partner Name" />
<label for="addlaneipicy">IPI/CY</label><span id="addlaneipicyError" class="text-danger laneError" style="display:none;"> * </span>
<select class="form-control validation" id="addlaneipicy">
<option></option>
<option value="YES">YES</option>
<option value="NO">NO</option>
</select>
// few more inputs and selects
<button type="button" class="btn btn-default btn-flat addLaneSubmit" id="addLaneSubmit" name="addLaneSubmit">Add</button>
</form>
Here is the onClick event:
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let partnerCode = $('#addlanepartnercode').val();
let partnerName = $('#addlanepartnername').val();
let ipiCy = $('#addlaneipicy').val();
let addlane = new ProcessLane();
let addlanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
ipiCy: ipiCy
}
// how I typically would check the values below:
if(addlanecriteria.partnerCode == ""){
$('#addlanepartnercodeError').show();
return false;
}
if(addlanecriteria.partnerName == ""){
$('#addlanepartnernameError').show();
return false;
}
else{
addlane.addLaneProcessing(addlanecriteria);
}
});
The way I typically check the values is redundant and time consuming.
I did add a class to the inputs called 'laneError'. I was trying to use that to display the errors by calling a function, as follows:
function showAllErrors(){
if($(".addLaneForm .validation") == ""){
$('.laneError').show();
}
}
For one, I wasn't sure where I could put the function call.
But when I was able to call the function, I can only get the first error to show, which is "addlanepartnercodeError".
There has to be a simpler way to check the values in the object.
You can just have a reusable function like below:
showErrorMsg(elemId) {
if($.trim($('#' + elemid).val()) === '') {
$('#' + elemId + 'Error').show()
return true;
}
return false;
}
So your code would just be:-
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let Error = false,
addlane = new ProcessLane();
$('form')
.find("input[id^='add']")
.each((i , e){
if(!Error) {
Error = showErrorMsg($(e).attr('id'))
}
})
if(!Error) {
// Your form has no errors , do your thing here
addlane.addLaneProcessing(addlanecriteria);
}
});

I'm trying to validate multiple HTML Form inputs with javascript, and change css for invalid ones, what is the best way to do this?

I'm trying to validate an HTML form, trying to check if answers are filled in, and an e-mail is an actual e-mail adress. I want to proceed when all fields are valid. When some fields are not valid, change the css in to another class (so it becomes red to show that it is wrong.)
I have tried to validate each input seperately, but i believe there should be an easier way. Can somebody show me?
Current HTML:
<div class="form-group" id="stage1">
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
</div
I can't use HTML default validation, since I have created a multi-step form.
Thanks in advance,
Brandon
You can iterate through inputs this will assist validating your messy items:
window.onload = () => {
const allInputs = document.querySelectorAll(".form-control"); // or you may assign custom class or select by input tag..
let isAllvaild = true;
allInputs.forEach((element) => {
if (!validateAll(element.value, element.type)) { isAllvaild = false; break; }
});
if (isAllvaild) {
afterValidation(); // to keep things clean
}
}
function validateAll(value, type) {
if (type === "text") {
} else if (type === "email") {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let ck = re.test(String(value).toLowerCase());
if (ck) {
// set errors here..
} else {
// maybe remove errors if added previously..
}
return ck;
} else if (type === "phone") {
} else if (type === "other") {
} // add whatever needed..
}
function afterValidation() {
// at this point each input contains valid data.. proceed to next step..
// document.querySelector("#my_id").classList.add("display-block");
// ..
}
you can validate based on their type, so i think u would have two functions, one for email and another one for text fields. for instance:
if(textValidation() && emailValidation()){
submit()
}
emailValidation(){
return email ? true : false
}
textValidation(){
return text ? true : false
}
What about that? It will let you loop through every input and you can also do some specific validations. I know, it is not the smartest function ever, but it can be useful. (ofc you should make some better checking for email pattern (regular expressions are good for that /^.+?#.+..+$/m) and registration number (regex could be cool for that too: /^[\d]*$/m)
function validateInputs ()
{
const inputs = document.querySelectorAll('div[class=row] input');
for (let index = 0; index < inputs.length; index++)
{
const input = inputs[index];
let valid = false;
if (input.value && input.value.trim() !== '')
{
//here you can add specific validations for each id, maybe you can also use switch here
if (input.getAttribute('id') === 'email')
{
//of course, email also need to validate, if dot is present, regular expression might be the best option
if (input.value.indexOf('#') !== -1)
{
valid = true;
}
}
else
{
valid = true;
}
}
if (!valid)
{
input.classList.add('error');
}
else
{
input.classList.remove('error');
}
}
};
window.addEventListener('load', function () {
document.querySelector('button').addEventListener('click', validateInputs)
});
input.error {
background-color: red;
}
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
<button>validate</button>
For fields like text you need to write your own validation, since it is totally up to you. But in case of fields like email or url you can use build in functions like the HTMLFormElement.checkValidity() method to see if the form contains a field that does not have a valid input, for example a input with type email and a value of foobar would return false from the validity check.
Then you can look inside the form and search for all inputs that are invalid with the :invalid selector in querySelectorAll(). It will return a NodeList with the invalid form elements inside of it.
const form = document.querySelector('form');
form.addEventListener('input', event => {
if (form.checkValidity() === false) {
const invalids = form.querySelectorAll(':invalid');
for (const input of invalids) {
console.log(`${input.id} is invalid`);
}
}
});
<form>
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="url" id="website" class="form-control" placeholder="Website*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</form>
You can use this code between a script tag :
const form = document.querySelector('form'); form.addEventListener('input', event => { if (form.checkValidity() === false) { const invalids = form.querySelectorAll(':invalid'); for (const input of invalids) { console.log(`${input.id} is invalid`); } } });
Or use a Bootstrap classes to validate your form

javascript keyup to change divs not just text

I have some code that checks if 2 text fields match. This is using the keyup which works fine but I would like it to hide or show a div depending on result. All I have is a code that changes divCheckPasswordMatch?
So I would like it to
$('#match').hide();
$('#nomatch').show();
The js code is :
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
$("#divCheckPasswordMatch").html(password == $(this).val() ? "Passwords match." : "Passwords do not match!");
});
});
My guess is you want to have two <div> displaying different messages using show() and hide(), but I'm not sure, so I did both.
$('#match').hide();
$('#nomatch').hide();
$("#password2").keyup(function() {
var password = $("#password1").val();
if ($(this).val() === password) {
$('#divCheckPasswordMatch').html('Passwords match');
$('#match').show();
$('#nomatch').hide();
} else {
$('#divCheckPasswordMatch').html('Passwords do not match');
$('#match').hide();
$('#nomatch').show();
}
});
<form action="/action_page.php">
First input: <input id="password1" type="text" name="fname"><br>
Second input: <input id="password2" type="text" name="lname"><br>
</form>
<div id="divCheckPasswordMatch"></div>
<div id="match">Match</div>
<div id="nomatch">No Match</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Well following what you want you can do this.
HTML
<input id="password1">
<input id="password2">
<spam id="divCheckPasswordMatch"></spam>
JS
$(function() {
$("#password2").keyup(function() {
var password = $("#password1").val();
var password2 = $("#password2").val();
if(password!== null && password2!== null){
if(password == password2) {
$('#divCheckPasswordMatch').show();
$("#divCheckPasswordMatch").html("Passwords match.")
}
else {
$('#divCheckPasswordMatch').hide();
$("#divCheckPasswordMatch").html("Passwords do not match!")
}
}
});
});
But remember that you also need to anticipate if the password1 is changed too.
Here is working example. For learning purposes I highly suggest using pure javascript instead of jQuery. It is easy to rewrite it to jQuery. I can do it for you if you want.
You are missing blur event, I've added it. Code is not repeatable, it can be still improved. We are using one function for validation.
var field1 = document.getElementById('password1');
var field2 = document.getElementById('password2');
var result = document.getElementById('divCheckPasswordMatch');
function validateInputs() {
// If any of fields is empty then quit
if (field1.value === '' || field2.value === '') {
return;
}
if (field1.value === field2.value) {
result.innerHTML = '';
// optional hide it, clearing text gives almost the same effect, up to you
// result.style.display = 'none';
} else {
result.innerHTML = 'Passwords don\'t match';
// optional show it
//result.style.display = 'block';
}
}
document.getElementById('password1').addEventListener('keyup', validateInputs);
document.getElementById('password2').addEventListener('keyup', validateInputs);
document.getElementById('password1').addEventListener('blur', validateInputs);
document.getElementById('password2').addEventListener('blur', validateInputs);
<input type="text" id="password1">
<input type="text" id="password2">
<div id="divCheckPasswordMatch"></div>

Search for equal numbers or alphanumeric values inserted in input elements

I want to loop through all the input elements and find if the same value exists.
For example when a user inserts 1(one) and then inserts again the number 1(one), I would like to apply CSS to change the background color of the input element for these 2 equal values or no matter how many they may be.
If the user tries to insert an alphanumerical value then JavaScript handles the code and adds the selected-wrong-input CSS class.
I would like on that element to have a setInterval for 2 seconds and take out the alphanumerical value from the input in order for the user to be able to insert a number again.
I don't mind if the proposed solution is with JavaScript, jQuery or a combination of both.
The html code:
<div class="bus-builder-seat-box-container" id="dynamic-bus-builder-1">
<input id="posA100" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA101" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA102" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA103" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA104" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA105" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA106" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA107" type="text" class="input seat_box selected-wrong-input" onchange="bc.seatBoxHandleEvent(this)">
</div>
The JavaScript code. The first is the event which is called in the html input element onchange
bc.seatBoxHandleEvent = function (el) {
bc.checkInput(el);
var seatNumberFirstFloor = $('#dynamic-bus-builder-1');
if (seatNumberFirstFloor && seatNumberFirstFloor.valueOf()) {
var leftStreaming = (event.target.id);
var rightStreaming = 'posB1' + leftStreaming.substring(5, 7);
document.getElementById(rightStreaming).innerHTML = event.target.value;
}
}
bc.checkInput = function (el) {
let $el = $(el);
var targetValue = event.target.value;
var id = event.target.id;
var classOfInput = event.target.classList;
if (targetValue !== 8 && targetValue !== 0 && (targetValue < 48 || targetValue > 57)) {
console.log('valid number');
console.log(classOfInput);
$(el).toggleClass('selected');
}
else {
console.log('invalid character');
$(el).toggleClass('selected-wrong-input');
//console.log(el.value);
}
var array = new Array(120);
var existsValue = false;
for(var i = 0; i <= array.length; i++) {
console.log(el.value);
console.log(i);
if (el.value === array[i]) {
console.log('hi');
console.log(el.value);
console.log(array[i]);
var existsValue = true;
console.log('existsValue');
console.log('equal number forbidden');
//break;
}
}
I'd suggest to use IsNaN() function to check if the input is a number. Also a keyup event is better for input fields.
var inputList = [];
$('.seat_box').keyup(function(elem){
if(IsNaN(elem.value)) return; //input isn't numeric, add your functionality
if (!valueExists(elem)) inputList.push(elem.value);
else //dublicate value, add functionality
});
function valueExists(elem) {
$(".seat_box").each(function(elem) {
if ($.inArray(this.value, inputList) != -1) return true;
else return false;
});
}

Categories

Resources