My JavaScript form validation function is called two times - javascript

I am trying to print the value from the form when a user submits the function but a blank value is returned.
Here is my JavaScript code:
var login = new function()
{
var name = null ;
this.validation = function()
{
this.name = document.getElementById("Username").value;
console.log(this.name);
document.getElementById("demo").innerHTML = this.name;
};
};
And my HTML form as :
<body>
<div class="container">
<div class="col-md-8">
<div class="starter-template">
<h1>Login with javascript</h1>
<p class="lead">Please Enter Following Details</p>
<h1 id="demo"></h1>
<form name="form" onSubmit="return login.validation();" action="#" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Username</label>
<input type="text" name="username" class="form-control" id="Username" placeholder="Please Enter your Username">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="Email" placeholder="Please enter your Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="Password" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Re-Password</label>
<input type="password" class="form-control" id="Re-Password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
<script src="js/login.js"></script>
<script href="js/bootstrap.js"></script>
<!-- /.container -->
</body>
Why does the value not get into html <p> tag.

Your code simply works. But since the function executes on submitting the form, the username gets logged in the console fast before the page refreshed with submitted data. You can confirm this and test it by adding event.preventDefault(); to the function to prevent submitting the form so the page would stay visible with the console.
<script>
var login = new function()
{
var name = null ;
this.validation = function()
{
event.preventDefault();
this.name = document.getElementById("Username").value;
console.log(this.name);
document.getElementById("demo").innerHTML = this.name;
};
};
</script>
If that's not what you're looking for, let me know.

We the javascript validation failed you need to return false. If you don't it will proceed your form further. Thanks
var login = new function()
{
var name = null ;
this.validation = function()
{
this.name = document.getElementById("Username").value;
document.getElementById("demo").innerHTML = this.name;
return false;
};
};

Related

setCustomValidity error but the form is submitted

I'm using setCustomValidity function to check if the new password and the repeat password are equals but , I debugged the code and the comparisson its correct but the error message its not shown and the form post request its done
<form action="/register" method="post" onsubmit="check_new_password()">
<div class="form-group">
and the javascript
function check_new_password(){
var new_pass = $('#new-password').val();
var repeated_pass = $('#repeat-password').val();
if(new_pass != repeated_pass){
$('#repeat-password')[0].setCustomValidity('Password are not equals');
}else{
$('#repeat-password')[0].setCustomValidity('');
}
You need to add the return statement in the onsubmit attribute, like this:
onsubmit="return check_new_password();"
So, the check_new_password() function needs to return a boolean according the validation.
Don't forget call the .reportValidity(); method because you're using HTMLObjectElement.setCustomValidity() method.
Additionally, you should add oninput="setCustomValidity('');" on the inputs fields to force to update its state.
See in this example:
function check_new_password() {
var new_pass = $('#new-password').val();
var repeated_pass = $('#repeat-password').val();
if (new_pass != repeated_pass) {
$('#repeat-password')[0].setCustomValidity('Password are not equals.');
$('#repeat-password')[0].reportValidity();
return false;
} else {
$('#repeat-password')[0].setCustomValidity('');
return true;
}
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<form action="/register" method="post" onsubmit="return check_new_password();">
<div class="form-group">
<label for="new-password">Password:</label>
<input id="new-password" class="form-control" type="password" oninput="setCustomValidity('');" />
</div>
<div class="form-group">
<label for="repeat-password">Repeat Password:</label>
<input id="repeat-password" class="form-control" type="password" oninput="setCustomValidity('');" />
</div>
<div>
<button class="btn btn-xs btn-primary" type="submit">Send</button>
</div>
</form>
</div>

Trying to implement closure on event handler? Error: undefined

I have trying to get the values out of a form when the register button is clicked.
setupFormUI() and the relevant form fields are saved in variables
$($rego_form).on("submit", getRegistrationFormValue); is called - a handler should be able to have access to setupFormUI() variables (closure) but it seems to not do anything
ISSUE: getRegistrationFormValue doesn't log anything. I can make it work if I pass arguments to the function... but I want to use
closure
setupFormUI();
function setupFormUI() {
var $name = $("#name");
var $age = $("#age");
var $department = $("#department");
var $position = $("#position");
var $rego_form = $("#rego-form");
$($rego_form).on("submit", getRegistrationFormValue);
}
function getRegistrationFormValue() {
// alert("asdasd");
var name = $name.val();
var age = $age.val();
var department = $department.val();
var position = $position.val();
console.log("----->", name, age, position, department);
}
html
<form id="rego-form">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label>Company (disabled)</label>
<input type="text" class="form-control" disabled placeholder="Company" value="Creative Code Inc.">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>name</label>
<input type="text" id="name" class="form-control" placeholder="name" value="michael">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputEmail1">Age</label>
<input id="age" class="form-control" placeholder="age">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Department Name</label>
<input type="text" id="department" class="form-control" placeholder="department" value="Marketing">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Position</label>
<input type="text" id="position" class="form-control" placeholder="position" value="social media manager">
</div>
</div>
</div>
<button type="submit" id="rego-user-btn" class="btn btn-info btn-fill pull-right">Register</button>
<div class="clearfix"></div>
</form>
You need the variables to be in scope, you can use an anonymous closure as a callback to achieve this.
setupFormUI();
function setupFormUI() {
var $name = $("#name");
var $age = $("#age");
var $department = $("#department");
var $position = $("#position");
var $rego_form = $("#rego-form");
$rego_form.on("submit", function(){
var name = $name.val();
var age = $age.val();
var department = $department.val();
var position = $position.val();
console.log("----->", name, age, position, department);
});
}
An alternative to the accepted answer — give the "handler" a meaningful context of this with Function.prototype.bind(), or maybe just use the ES6 class.
setupFormUI();
function setupFormUI() {
var args = {
$name: $("#name"),
$age: $("#age"),
$department: $("#department"),
$position: $("#position"),
$rego_form: $("#rego-form")
}
args.$rego_form.submit(getRegistrationFormValue.bind(args));
}
function getRegistrationFormValue(e) {
var name = this.$name.val();
var age = this.$age.val();
var department = this.$department.val();
var position = this.$position.val();
console.log("----->", name, age, position, department);
e.preventDefault();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="rego-form" action="#">
<input id="name" value="John Doe" />
<input id="age" value="37" />
<input id="department" value="Some dept" />
<input id="position" value="Debt collector" />
<button type="submit">Submit</button>
</form>
This is no closure, if the variable in setupFormUI is referenced, it is a closure.
getRegistrationFormValue is just a variable whose function is passed directly to the event trigger (and is asynchronous), note that it is not executed in setupFormUI, nor is it defined in setupFormUI, When it is executed, it has nothing to do with setupFormUI.
Mike Zinn's answer defines an anonymous function in setupFormUI, which in turn refers to the variable in setupFormUI, which is a closure.

Form validation with java script

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 ?

JavaScript form validation not working as intended

Good morning,
I'm working on some simple form validation. Whenever I submit my form, the error message appears, but I can repeatedly spam the button for numerous error messages. Is there a way I can change this to only show the error message once? I've also noticed that even if I populate both fields it will still flash quickly in my console with the error log but not show the error.
Can anyone tell me what I'm doing wrong here?
var uname = document.forms['signIn']['userame'].value;
var pword = document.forms['signIn']['password'].value;
function validateMe (e) {
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe();">Sign In</button>
</div>
</div>
</form>
Fiddle
You must be clearing the contents of your container to avoid duplication of elements. Below are few things to note:
You were trying to get userame instead of username in your fiddle. May be spelling mistake.
Keep input type=submit instead of button
Pass the event to your validateMe function to prevent the default action of post.
Move the variables within the function to get the actual value all the time
function validateMe(e) {
e.preventDefault();
var uname = document.forms['signIn']['username'].value;
var pword = document.forms['signIn']['password'].value;
var container = document.getElementById('error-container');
container.innerHTML = ''; //Clear the contents instead of repeating it
if (uname.length < 1 || pword.length < 1) {
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<input value="Sign In" class="button clear right-floater" type="submit" onclick="validateMe(event);" />
</div>
</div>
</form>
Updated Fiddle
Edit - if condition was failing and have updated it accordingly
this is full work code
var uname = "";
var pword = "";
function validateMe(e) {
e.preventDefault();
uname = document.forms['signIn']['username'].value;
pword = document.forms['signIn']['password'].value;
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
return true;
}
<form id="signIn">
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe(event);">Sign In</button>
</div>
</div>
</form>

Aurelia: Trigger Validation on tab-out(blur event)

I have returned a validation group to validate my inputs which triggers on submit button and I want to trigger by validation on blur event to trigger respective validation, not all.
For example:
HTML:
<form role="form" submit.delegate="welcome()" validate.bind="validation">
<div class="form-group">
<label for="fn">First Name</label>
<input type="text" value.bind="firstName & updateTrigger:'blur'" class="form-control" id="fn" placeholder="first name" />
<span>${firstName}</span>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Validation Rule in ViewModel:
this.validation = validation.on(this)
.ensure('firstName')
.isNotEmpty()
.hasMinLength(3)
.hasMaxLength(10);
Since I have written updateTrigger:'blur' none of the validation are getting triggered.
Once you remove updateTrigger:'blur' all the validations are working expected.
Requirement:
I want that once the input box loses focus(blur is triggered) then validation(s) related to 'firstname' are triggered no other validation(of other properties).
Thanks in advance.
This is now supported in the aurelia-validation alpha. Check out this blog post: https://www.danyow.net/aurelia-validation-alpha/
Here's an example: https://gist.run?id=381fdb1a4b0865a4c25026187db865ce
registration-form.html
<template>
<require from="./validation-summary.html"></require>
<h1>Register!</h1>
<form submit.delegate="submit()"
validation-renderer="bootstrap-form"
validation-errors.bind="errors">
<validation-summary errors.bind="errors"
autofocus.bind="controller.validateTrigger === 'manual'">
</validation-summary>
<div class="form-group">
<label class="control-label" for="first">First Name</label>
<input type="text" class="form-control" id="first" placeholder="First Name"
value.bind="firstName & validate">
</div>
<div class="form-group">
<label class="control-label" for="last">Last Name</label>
<input type="text" class="form-control" id="last" placeholder="Last Name"
value.bind="lastName & validate">
</div>
<div class="form-group">
<label class="control-label" for="email">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email"
value.bind="email & validate">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-default" click.delegate="reset()">Reset</button>
</form>
</template>
registration-form.js
import {inject, NewInstance} from 'aurelia-dependency-injection';
import {ValidationController, validateTrigger} from 'aurelia-validation';
import {required, email, ValidationRules} from 'aurelia-validatejs';
#inject(NewInstance.of(ValidationController))
export class RegistrationForm {
#required
firstName = '';
#required
lastName = '';
#required
#email
email = '';
constructor(controller) {
this.controller = controller;
// the default mode is validateTrigger.blur but
// you can change it:
// controller.validateTrigger = validateTrigger.manual;
// controller.validateTrigger = validateTrigger.change;
}
submit() {
let errors = this.controller.validate();
// todo: call server...
}
reset() {
this.firstName = '';
this.lastName = '';
this.email = '';
this.controller.reset();
}
}
Aurelia's validation was updated in late 2016 to include a changeOrBlur validateTrigger option, which in my opinion should be the new default. Here's how to use it:
constructor(controller) {
this.controller = controller;
controller.validateTrigger = validateTrigger.changeOrBlur;
// controller.validateTrigger = validateTrigger.blur; (default)
// controller.validateTrigger = validateTrigger.change;
// controller.validateTrigger = validateTrigger.changeOrBlur;
// controller.validateTrigger = validateTrigger.manual;
}

Categories