I'm new to Javascript and I need to validate a log-in form with Bootstrap, the thing is not validating the password in the script.
https://jsfiddle.net/98uqsvu2/
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
git: https://gist.github.com/Adaryn/6c38cfafd5e95d8a0bba508a33cebec7
#Adaryn
Since I cannot comment, I posted it as an answer.
I made the following changes to the fiddle and I was able to execute the code.
Removed the link href's from your HTML.
Added the closing body tag.
Moved the script from the javascript code section and pasted it just above the closing body tag.
Here is the updated fiddle.
<div class="container">
<form class="form-signin" form role="form" action="hola.html" name="formlogin" method="post" class="login-form" onsubmit="check_info()">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required="">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script type="text/javascript">
function check_info()
{
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if(user == "test#gmail.com")
{
if(pass == "123")
{
return true;
}
}
else
{
return false;
}
}
</script>
try this code. also added jsfiddle
document.getElementById("submit-form").addEventListener("click", check_info);
function check_info() {
var user = document.getElementById("inputEmail").value;
var pass = document.getElementById("inputPassword").value;
if (user == "test#gmail.com" && pass == "123") {
alert("email and password is valid!!!");
return true;
} else {
alert("email and password is NOT valid!!!");
return false;
}
}
https://jsfiddle.net/damaxrss/
Related
I have a form which shows an alert with a message when the two password input fields do not match but if they do match it shows a confirmation message before creating the user. The issue im having is that even if my confirmation function returns false which means that in the confirm message i selected cancel, my form is being submitted again.
<script>
function confirmarAlta(){
var result = confirm("Esta seguro que desea crear este usuario?");
if(result == false){
event.preventDefault();
}
}
</script>
<script>
function verificarPassword(){
var pass = document.querySelector(".password").value;
var confirmPass = document.querySelector(".confirmPassword").value;
console.log(pass);
console.log(confirmPass)
if(pass != confirmPass){
pass = "";
confirmPass = "";
alert("Las contraseñas no coinciden");
return
}
}
</script>
<script>
function Validaciones(event) {
if (verificarPassword() === true) {
confirmarAlta();
if(confirmarAlta()==false){
event.preventDefault();
}
} else {
event.preventDefault();
}
}
</script>
<form onSubmit="Validaciones(event)" method="post" action="ServletUsuarios">
<div class="form-group">
<label>Contraseña: </label>
<input type="password" class="form-control password" name="txtPassword" required>
</div>
<div class="form-group">
<label>Repetir Contraseña: </label>
<input type="password" class="form-control confirmPassword" name="txtConfirmarPassword" required>
</div>
<div class="col-12">
<input type="submit" class="btn btn-success" value="Aceptar" name="btnAceptar">
<button type="submit" class="btn btn-outline-info">Limpiar campos</button>
</div>
</form>
So I am guessing you wrapped the html provided inside a form, which is causing the submission, since input is of type submit, I removed that and moved it to the onSubmit event and called the event.preventDefault() which will stop the fault form action, only when the validation alert opens!
function confirmarAlta(event) {
var result = confirm("Esta seguro que desea crear este usuario?");
if (result === false) {
event.preventDefault();
}
}
function verificarPassword() {
var pass = document.querySelector(".password").value;
var confirmPass = document.querySelector(".confirmPassword").value;
console.log(pass);
console.log(confirmPass)
if (pass != confirmPass) {
pass = "";
confirmPass = "";
alert("Las contraseñas no coinciden");
return false
}
return true;
}
function Validaciones(event) {
if (verificarPassword() === true) {
confirmarAlta(event);
} else {
event.preventDefault();
}
}
<form onSubmit="Validaciones(event)">
<div class="form-group">
<label>Contraseña: </label>
<input type="password" class="form-control password" name="txtPassword" required>
</div>
<div class="form-group">
<label>Repetir Contraseña: </label>
<input type="password" class="form-control confirmPassword" name="txtConfirmarPassword" required>
</div>
<div class="col-12">
<input type="submit" class="btn btn-success" value="Aceptar" name="btnAceptar">
<button type="submit" class="btn btn-outline-info">Limpiar campos</button>
</div>
</form>
Try using a match function or contains function to identify if your pass and confirmPass return true or false. Also convert this to toUpper case or toLower case before comparison. I guess it is returning true always under pass != confirmpass.
Also, please share what is inside pass and confirmpass before if condition.
I created a mini application with custom login always in the same page, to explain better I have a main page with the login and registration and when I do the login/registration I remain on the same page and where was the login form appear a "Welcome Back" panel.
The problem is that when I try to reload the page with F5 I get for like 2 seconds the old login form and then appear the "Welcome Back" panel. I've used the If statements of Blaze to manage the check of the current user logged in as we can see:
<template name="login">
{{#if currentUser}}
<div class=" card mb-4 shadow-sm">
<div class="card-header">
<h4 class="my-0 font-weight-normal">Welcome Back</h4>
</div>
<div class="card-body">
TEST
</div>
</div>
{{else}}
<div id="panel-login" class=" card mb-4 shadow-sm">
<div class="card-header">
<h4 class="my-0 font-weight-normal">Login Form</h4>
</div>
<div class="card-body">
<form class="login-form">
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" name="email" id="InputEmailLogin" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="InputPassword">Password</label>
<input type="password" name="password" class="form-control" id="InputPasswordLogin" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
<span>or Create an account</span>
</form>
</div>
</div>
<div id="panel-register" class=" card mb-4 shadow-sm">
<div class="card-header">
<h4 class="my-0 font-weight-normal">Register Form</h4>
</div>
<div class="card-body">
<form class="register-form">
<div class="form-group">
<label for="InputEmail">Email address</label>
<input type="email" class="form-control" name="email" id="InputEmail" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="InputPassword">Password</label>
<input type="password" name="password" class="form-control" id="InputPassword" placeholder="Password">
</div>
<div class="form-group">
<label for="InputPassword">Repeat Password</label>
<input type="password" name="password2" class="form-control" id="InputPasswordConfirm" placeholder="Repeat Password">
</div>
<button type="submit" class="btn btn-primary">Register</button>
<span>or Login</span>
</form>
</div>
</div>
{{/if}}
</template>
That's my JS file where I manage the entire events of login/registration system:
Template.login.events({
'click .register-link': function() {
$('#panel-login').hide();
$('#panel-register').show().addClass("animated fadeIn");
},
'click .login-link': function() {
$('#panel-register').hide();
$('#panel-login').show().addClass("animated fadeIn");
},
// Registration
'submit .register-form': function(event) {
var email = trimInput(event.target.email.value);
var password = trimInput(event.target.password.value);
var password2 = trimInput(event.target.password2.value);
if(isNotEmpty(email) && isNotEmpty(password) && isNotEmpty(password2)
&& isEmail(email) && areValidPasswords(password,password2)) {
Accounts.createUser({
email: email,
password: password,
profile: {
userType: 'Normal'
}
}, function(err) {
if(err) {
sAlert.error("There was an error with the registration, try again!");
} else {
sAlert.success("Account Created! You are now logged in");
}
});
}
// Prevent Submit
return false;
},
// Login
'submit .login-form': function(event) {
var email = event.target.email.value;
var password = event.target.password.value;
Meteor.loginWithPassword(email, password, function(err) {
if(err) {
event.target.email.value = email;
event.target.password.value = password;
sAlert.error("There is an error with your login, try again!");
} else {
sAlert.success("You are now logged in!");
}
})
// Prevent Submit
return false;
}
});
Template.login.helpers({
ifLogged: function(user) {
if(user != null) {
$('#panel-login').hide();
}
}
});
// Trim the input
var trimInput = function(val) {
return val.replace(/^\s*|\s*$/g, "");
};
// Check for empty fields
isNotEmpty = function(value) {
if(value && value !== "") {
return true;
}
sAlert.error('Please fill all the fields');
return false;
};
// Validating Email
isEmail = function(value) {
var filter = /^(([^<>()\[\]\\.,;:\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,}))$/;
if(filter.test(value)) {
return true;
}
sAlert.error("Invalid email, please use a valid email address");
return false;
};
// Check passwords fields
isValidPassword = function(password) {
if(password.length < 6) {
sAlert.error("Password must be at least 6 characters");
return false;
}
return true;
}
// Check confirmation password
areValidPasswords = function(password, confirm) {
if(!isValidPassword(password)) {
return false;
}
if(password !== confirm) {
sAlert.error("Password do not match");
return false;
}
return true;
};
Here there's a GIF to show you the problem:
https://i.gyazo.com/120efc183793d4d1adc5fb518e01c09c.mp4
Thanks if someone can help me.
If you just wanna to git rid of that flick then you can implement loading on Meteor.loggingIn as sample below, alter it with your use case i.e wrap it in a template Helper and replace that helper with currentUser
if (Meteor.loggingIn()) {
return 'loading';
} else if (Meteor.user()) {
return 'home';
} else {
return 'signin';
}
Trying to validate a form but I am facing constant problems. Here is the code
HTML:
<form id="regForm" class="form-group" method="POST" action="signup.php">
<div class="col-md-12">
<h2>Job Pocket</h2>
</div>
<div class="col-md-12">
<input placeholder="email" class="form-control"type="text" name="email" id="email">
</div>
<div class="col-md-12">
<input placeholder="password" class="form-control" type="password" name="password" id="password">
</div>
<div class="col-md-12">
<input placeholder="confirm password" class="form-control" type="password" name="confirmpass" id="confirmpass">
</div>
<div class="container">
<div class="row">
<div class="col-md-6">
<input placeholder="first name" class="form-control" type="text" name="first_name" id="first_name">
</div>
<div class="col-md-6">
<input placeholder="last name" class="form-control" type="text" name="last_name" id="last_name">
</div>
</div>
</div>
<div class="col-md-12">
<input type="submit" onclick="return validation()"class="btn btn-primary"name="submitsignup" id="submitsignup" value="submit">
</div>
<hr>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
<p id="mg"></p>
</div>
JavaScript:
<script type="text/javascript">
function validation(){
if(document.getElementById("email").value=="" || document.getElementById("password").value=="" || document.getElementById("last_name").value=="" || document.getElementById("first_name").value==""){
document.getElementById("mg").innerHTML="Fill all fields";
return false;
}
var emails = document.getElementById("email").value;
else if(emails.indexOf('#') <= 0){
document.getElementById('mg').innerHTML =" ** # Invalid Position";
return false;
}
else if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
document.getElementById('mg').innerHTML =" ** . Invalid Position";
return false;
}
else {
document.getElementById("regForm").submit();
}
}
</script>
The form keeps submitting itself. It works for the first if statement but after that it ignores the two else if and submits itself.
Even if I comment out this statement, it still submits to signup.php
document.getElementById("regForm").submit();
At the moment I have no idea why it is submitting so I am adding the php code aswell.
if(isset($_POST['submitsignup'])){
$date = array();
if($_POST['email']=='' || $_POST['password']=='' || $_POST['first_name']=='' || $_POST['last_name']==''){
$template->error="Please fill all fields";
}}
I added this bit of code in the signup.php file for an extra check but I have seen that it strightup submits to signup.php.
EDIT: Updated answer to updated question
Your problem might be related to the fact that you have this line of code:
var emails = document.getElementById("email").value;
before the elseif, which might break the if elseif flow.
Try using this code instead:
function validation(){
var emails = document.getElementById("email").value;
if(emails=="" || document.getElementById("password").value=="" || document.getElementById("last_name").value=="" || document.getElementById("first_name").value==""){
document.getElementById("mg").innerHTML="Fill all fields";
return false;
}
else if(emails.indexOf('#') <= 0){
document.getElementById('mg').innerHTML =" ** # Invalid Position";
return false;
}
else if((emails.charAt(emails.length-4)!='.') && (emails.charAt(emails.length-3)!='.')){
document.getElementById('mg').innerHTML =" ** . Invalid Position";
return false;
}
else {
document.getElementById("regForm").submit();
}
}
Try with:
<input type="button"
instead:
type="submit"
Edit: otherwise your .submit() function is useless.
-2 ? Tell me why using .submit() if the form as already submit type ?
I just starting programming this year and i have to do a website project with javascript validation. I know this is simple but i just forgot how to do it. Im trying to do a log in, username and password, where if the user enters admin in both it will take him to a php page and if either one is incorrect it will return false.
<form name="form2" id="form2" action="members.php" onsubmit="login()" method="post">
<fieldset>
<legend>Admin Login </legend>
<label>Username</label>
<input type="text" name="username" id="username">
<br>
<label>Password </label>
<input type="password" name="password" id="password">
<input type="submit" value="Log In">
</fieldset>
</form>
note im actually lost and no idea what im doing in the js part
function login () {
var username = document.form2.value.username;
var password = document.form2.value.password;
if ( username === "admin") {
alert("Incorrect");
return true;
} else {
return false;
}
if (password === "admin") {
return true;
} else {
alert("Incorrect");
return false;
}
}
You could do this on the client in JavaScript:
if (login()) {
document.location = 'members.php';
}
Better would be to just submit the data to the PHP-script and check it there, so nobody can read out the username/password.
if ('admin' === $_POST['username'] && 'admin' === $_POST['password']) {
echo 'Hello, admin.';
} else {
echo 'Invalid login, retry.';
}
When I hit the submit button at the first time these codes works. But when I hit the second time to the button even if email and password values were true nothing happens and the user can not login. But if I write the true values at the first time, it works and user can login. So I figured the cause of this problem is about the "return false;" phrase. But if I remove return false; phrase, the form posts and ajax codes become useless. I must avoid the posting without ajax.
jQuery:
<script>
$(document).ready(function(){
$('#submit-btn').click(function(){
var email = $('#email').val();
email = $.trim(email);
var password = $('#password').val();
password = $.trim(password);
if(email == "") {
$('#email').css({
"background-color": "#FF7070"
});
$('#box1').css({
"visibility": "visible"
});
return false;
}else if(password == "") {
$('#password').css({
"background-color": "#FF7070"
});
$('#box2').css({
"visibility": "visible"
});
return false;
}else{
$.ajax({
type: "POST",
url: "ajax.php",
data: $('#loginform').serialize(),
timeout: 5000,
success: function(c) {
if(c == "no") {
$('#box3').css({
"visibility": "visible"
});
return false;
} else if (c == "ok") {
window.location.href = "homepage.php";
}
},
error: function(a, b) {
if (b == "timeout") {
alert("Error: #101");
}
},
statusCode: {
404: function(){
alert("Error: #102")
}
}
});
}
return false;
})
});
</script>
Html:
<form name="loginform" id="loginform" method="post" action="">
<div class="field">
<input type="text" maxlength="40" id="email" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="password" id="password" name="password" placeholder="Password" autocomplete="off">
</div>
<div class="field">
<input type="submit" id="submit-btn" value="Log in">
</div>
<div class="keep-login">
<label for="remember">
<input type="checkbox" name="remember" id="remember" checked="checked">Remember me
</label>
<span>Forgot password?</span>
</div>
</form>
PHP:
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'email' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('email'), Input::get('password'), $remember);
if($login) {
echo "ok";
} else {
echo "no";
}
} else {
echo "no";
}
}
}
First, remove the method and action attributes of the form element. You can remove the form tag altogether but if you want to support non-javascript submissions, you'll need the form tag (however, the original question did not ask for this). You're 'submitting' the form via jQuery, so you don't need a method and an action on a form tag.
Input type="password" never autocompletes, so you don't need that attribute.
I also added an error div. Here is your new html:
<div id="error" style="display: none;">Login failed.</div>
<form>
<div class="field">
<input type="text" maxlength="40" id="email" name="email" placeholder="E-mail">
</div>
<div class="field">
<input type="password" id="password" name="password" placeholder="Password">
</div>
<div class="field">
<input type="submit" id="submit-btn" value="Log in">
</div>
<div class="keep-login">
<label for="remember">
<input type="checkbox" name="remember" id="remember" checked="checked">Remember me
</label>
<span>Forgot password?</span>
</div>
</form>
Replace your $.ajax statement with a $.post statement, and simply your logic.
$.post("ajax.php", { e: email, p: password }, function (data) {
if (data == "ok") window.location.href = "homepage.php";
else $("#error").slideDown().delay(3000).slideUp(); // I added div#error with "Failed to Login" message in the html above
});
This code will now redirect if the returned data is "ok"; otherwise, it will show div#error (again, this is in the html above), delay for 3 seconds, and then hide the message.
The return false; is unnecessary in each instance in your code above because after each conditional, the code ends - there is no other code to prevent from executing (which is why you would use return false; in this context).
You can do the $.trim on the same line as when you assign the variables, like I did with the slideUp, delay, and slideDown.