Move to second form after first form validation javascript - javascript

I am not sure what is wrong with my code. I am using two forms in jquery mobile and upon validation of the first, when the anchor tag is clicked, if the validation is successful, i would like to go to form 2 on #page2 or if validation fails, i would like to stay on the current page. The problem is if all the data on the first form is correct, I can navigate to the second form but if it isnt correct, the event.preventDefault() gets fired and if I fill the form in correctly, it wouldnt let me go to form 2.
<form action="#" method="post" data-ajax="false">
<span class="error_form" id="username_error"></span>
<label for="username">Username : <span></span></label>
<input type="text" name="username" id="username" placeholder="Enter username" value="">
<span class="error_form" id="password_error"></span>
<label for="password">Create password : <span></span></label>
<input type="password" name="password" id="password" placeholder="Enter password">
<span class="error_form" id="password_error_confirmation"></span>
<label for="passwordAgain">Confirm password : <span></span></label>
<input type="password" name="password_confirmation" id="password_confirmation" placeholder="Enter password again">
<div class="ui-grid-a">
<div class="ui-block-a">
Back
</div>
<div class="ui-block-b">
Next
</div>
</div>
</form>
script.js, I have tried it with event.PreventDefault()
and it doent work
$('a#register1').click(function(event){
check_username();
check_password();
check_password_confirmation();
if(error_username == false && error_password == false && error_password_confirmation == false){
sessionStorage.setItem("username", $("#username").val());
sessionStorage.setItem("password", $("#password").val());
sessionStorage.setItem("password_confirmation", $("#password_confirmation").val());
$(this).attr("href", "#page3");
}else{
$(this).removeAttr("href");
}
});

$('a#register1').click(function(event){
check_username();
check_password();
check_password_confirmation();
if(error_username == false && error_password == false && error_password_confirmation == false){
sessionStorage.setItem("username", $("#username").val());
sessionStorage.setItem("password", $("#password").val());
sessionStorage.setItem("password_confirmation", $("#password_confirmation").val());
$('a#register1').attr("http://depressionapp1.westeurope.cloudapp.azure.com/register.html#page3");
//window.location.href="http://depressionapp1.westeurope.cloudapp.azure.com/register.html#page3";
}else{
$('a#register1').removeAttr("href");
}
});
//This is my new code but it still does not direct me to page3

$('a#register1').click(function(){
$('a#register1').attr("href", "http://depressionapp1.westeurope.cloudapp.azure.com/register.html#page3");
error_username = false;
error_password = false;
error_password_confirmation = false;
check_username();
check_password();
check_password_confirmation();
if(error_username == false && error_password == false && error_password_confirmation == false){
sessionStorage.setItem("username", $("#username").val());
sessionStorage.setItem("password", $("#password").val());
sessionStorage.setItem("password_confirmation", $("#password_confirmation").val());
}else{
$('a#register1').removeAttr("href");
}
});

Related

Sweetalert PoP-up message when fields are field is not working

I had a question about Sweetalert a week ago. Then I got an answer which helped me, but unfortunately, it is still not working. I wanted a Sweetalert pop-up message (success) when the user hits the submit button, but only if the fields are filled. I do not know what the problem is. Currently, nothing happens when the user hits the button.
Here is my code:
function Sweetalert1(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var email = document.getElementById("email").value;
if (name != " " && message != " " && email != " "){
Swal.fire(
'Köszönjük!',
'Megkaptuk a leveledet és hamarosan válaszolunk!',
'success',
)}
}
And the part of the HTML:
<form role="form" id="contactForm" action="contact.php" method="post">
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Név</label>
<input class="form-control" id="name" name="name" type="text" placeholder="Név" required="required" data-validation-required-message="Kérlek add meg a neved!">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Email Cím</label>
<input class="form-control" id="email" type="email" name="email" placeholder="Email" required="required" data-validation-required-message="Kérlek add meg az Email címed!">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2">
<label>Üzenet</label>
<textarea class="form-control" id="message" rows="5" placeholder="Üzenet" name="message" required data-validation-required-message="Kérlek írd be az üzeneted!"></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div id="success"></div>
<div class="form-group">
<button name="submit" type="submit" class="btn" id="sendMessageButton">Küldés</button>
</div>
</form>
I can't see where the button was fired
On this line,
<button name="submit" type="submit" class="btn" id="sendMessageButton">Küldés</button>
You have at least two options to fire the button
1st
You can change the line to this
<button name="submit" type="submit" class="btn" id="sendMessageButton" onclick="Sweetalert1()">Küldés</button>
2nd
You can add this to your javascript section
$("#sendMessageButton").click(function(){
Sweetalert1();
});
3rd
You can use the form's on-submit event
$("form").submit(function(){
Sweetalert1();
});
When this is done, modify your condition to
if (name !== "" && message !== "" && email !== "")
OR
if (name.trim() && message.trim() && email.trim())
your condition is not right, try doing this:
if (name && message && email)
{
// Code
}
An empty field isn't equal to a space (" "), it is equal to an empty string (""). So, you need to check if the fields equal an empty string, not a field with a space:
if (name != "" && message != "" && email != "") {
// code...
}
However, if you want to treat fields which have no text in them (and just spaces) as invalid as well, you can add the .trim() method to your name, message and email variables. By using trim you can turn inputs such as
" " into "", which will then be treated as an invalid input:
if (name.trim() != "" && message.trim() != "" && email.trim() != "") {
// code...
}
As an empty string is considered falsey (ie "" == false) you don't need to check whether you're input equals an empty string and instead can just check if x.trim() evaluates to true like so:
if (name.trim() && message.trim() && email.trim()) {
// code...
}

Angular: unable to avoid form submit on validation failure

Im trying to validate the following form:
<div ng-controller="LoginController">
<form name="form" class="ng-pristine ng-valid" accept-charset="UTF-8" action="/sessions/login?locale=" method="post" novalidate>
{{ errorUsername }}
<input id="username" name="username" type="text" placeholder="EMAIL ADDRESS" ng-model="username" required>
{{ errorPassword }}
<input id="password" name="password" type="password" placeholder="PASSWORD" ng-model="password" required>
<p><input name="commit" value="LOGIN" ng-click="submitForm()" type="submit"></p>
</form>
</div>
With the following method on LoginController:
$scope.submitForm = function() {
var is_valid = true;
if ( username.innerHTML == "" ) {
$scope.errorUsername = "Email required";
is_valid = false;
};
if ( password.innerHTML == "" ) {
$scope.errorPassword = "Password required";
is_valid = false;
};
if (! is_valid ) { $scope.form.submitted = true }
};
The form submition enters the method, and for a second you can see the the error messages are displayed. But the form is still submited.
I should add that the form is linked to a rails controller. But that shouldn't matter because my intention is never to call rail's controller action if the form has errors.
Thanks in advance.
All you need is to write return false;
$scope.submitForm = function() {
var is_valid = true;
if ( username.innerHTML == "" ) {
$scope.errorUsername = "Email required";
is_valid = false;
return false;
};
if ( password.innerHTML == "" ) {
$scope.errorPassword = "Password required";
is_valid = false;
return false;
};
if (! is_valid ) { $scope.form.submitted = true }
};
Try to replace
<input name="commit" value="LOGIN" ng-click="submitForm()" type="submit">
to
<input name="commit" value="LOGIN" ng-click="submitForm()" type="button">
You can try with this.
<form name="yourform" ng-submit="yourform.$valid && submitForm()"
This is is. Apparently you can't prevent default submit if the form has an action attribute:
Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.
So, you have to trick it by adding some code in the form:
<form name="login" class="ng-pristine ng-valid" accept-charset="UTF-8" action="/sessions/login?locale=" method="post" novalidate ng-submit="(submitted=true) && login.$invalid && $event.preventDefault()" ng-class="{true:'submitted'}[submitted]">
Basically we used $event.preventDefault() to stop the submit propagation only if the form is invalid; plus we set a $scope variable ‘submitted’ to true in order to have a class that gets appended to the form if the form has been submitted in an invalid state at least once, even if none of its fields have been ‘touched’ – so it’s still ng-pristine.
Solution found here: http://sandropaganotti.com/2014/03/01/angular-js-prevent-an-invalid-form-submission/

JS/jQuery event.submit/return true not woking

I am wondering if someone can help me as i cant figure this out. I have this validation script that checks an email form for contents and valid email and it is working correctly however it is not submitting the form if everything is okay..it just removes to error messages and does nothing.
I have a strange feeling it will be something stupid but i cant see anything wrong here.
HTML
<!DOCTYPE html>
<html>
<head>
<?php include('includes/head.php'); ?>
<script type="text/javascript" src="js/contactVal.js"></script>
</head>
<body>
<?php include('includes/navbar.php'); ?>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Contact Form</h3>
<p>Use this handy little contact form to get in contact with me about anything at all. If you have a job offer or any questions about me then feel free to drop me a message, ill get back to you as soon as possible.</p>
<hr>
<div id="form-response">
</div>
<form id="mailer" action="scripts/mailer.php" method="POST">
<h3>Name:</h3>
<input type="text" id="name" name="name" placeholder="Enter your name"></input><br />
<h3>Email:</h3>
<input type="email" id="email" name="email" placeholder="Enter your email address"></input><br />
<h3>Subject:</h3>
<input type="text" id="subject" name="subject" placeholder="Enter the subject of your message"></input><br />
<h3>Message:</h3>
<textarea id="message" name="message" placeholder="Enter your message here..."></textarea><br />
<input type="submit" name="submit" id="submit" value="Send"></input><br /><br />
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="human" id="human" value="" />
</form>
</div>
<div class="col-md-4">
<h3>Details</h3>
<p><img class="about-arrow" src="img/icons/arrow.png" />Email: contact#alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Website: www.alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Mobile: On request</p>
<hr>
<h3>Socials</h3>
<a class="big" href="http://www.facebook.com/oukp3ngu1nx"><img class="about-arrow" src="img/icons/arrow.png" />Facebook</a><br />
<a class="big" href="http://www.twitter.com/alex_volley_"><img class="about-arrow" src="img/icons/arrow.png" />Twitter</a><br />
<a class="big" href="https://www.linkedin.com/pub/alex-volley/97/27/906"><img class="about-arrow" src="img/icons/arrow.png" />LinkedIn</a><br />
</div>
</div>
</div>
<?php include('includes/footer.php'); ?>
</body>
</html>
JAVASCRIPT
$(document).ready(function(){
$('#form-response').hide();
$('#form-response').click(function(){
$('#form-response').fadeOut();
});
$('#submit').click(function(){
event.preventDefault();
var valid = '';
var name = $('form #name').val();
var email = $('form #email').val();
var subject = $('form #subject').val();
var message = $('form #message').val();
var honey = $('form #honeypot').val();
var human = $('form #human').val();
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
//check for human interaction
if(honey == 'http://' && human == ""){
//check fields
if(name == '' || null || name.length < 2){
valid = '<p>You need to enter your name.</p>';
}
if(email == '' || null || email.length < 5){
valid += '<p>You need to enter an email address.</p>';
}
if(!email.match(filter)){
valid += '<p>You need to enter a valid email address.</p>';
}
if(subject == '' || null || subject.length < 2){
valid += '<p>You need to enter a valid subject.</p>';
}
if(message == '' || null || message.length < 30){
valid += '<p>You need to enter a message of at least 30 characters.</p>';
}
//check if valid
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
return true;
}
} else {
//spambot
error = '<p>Back of bot boy.</p>';
}
});
});
You did not pass event in the function arguments:
$('#submit').click(function( event ){
event.preventDefault();
You're probably better off using the submit event and letting the submit button do it's job:
$('#mailer').submit(function( event ){
event.preventDefault();
........
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
this.submit(); //ONCE EVERYTHING CHECKS OUT
} else {
.....
JS FIDDLE DEMO
EDIT
To resolve the error Uncaught TypeError: object is not a function, please change the name of your submit button to something else: this.submit -- the button, is conflicting with this.submit() -- the function.
Here is a version that works fine after changing: name="submit" to name="submit-button"
By the way your input elements do not need a closing tag </input>
REF: Uncaught TypeError: object is not a function, button inside form
May be you can try following code. On Submit button click validate form and if everything is fine submit form using .submit method.
$('#submit').click(function( event ){
event.preventDefault();
............
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
$('#mailer').submit(); //ONCE EVERYTHING CHECKS OUT
}
..............

How to validate a page using jQuery for passwords

I have a div and it contains three input text boxes(oldpassword,newpassword,confirmpassword).
<div class="searchContainer" id="chngpassword">
<div class="tableContent">
<div class="leftContent">
<div>Old Password<span class="redCLR">*</span></div>
<div>New Password<span class="redCLR">*</span></div>
<div>Confirm Password<span class="redCLR">*</span></div>
</div>
<div class="rightContent">
<div><input type="password" name="OldPassword" id="OldPassword" /></div>
<div><input type="password" name="NewPassword" id="NewPassword" /></div>
<div><input type="password" name="ConfirmPassword" id="ConfirmPassword" /></div>
</div>
</div>
<div class="searchButton" style="margin:10px 0 0 0">
<button id="btnSave">SAVE</button>
</div>
</div>
Now i have to validate the page in jquery for following scenarios:
1.Old password should not be blank.
2.New password should not be blank.
3.confirm password should not be blank.
4.old and confirm password should be same.
5.new password length should be 8-16 characters,atleast 1 special character,atleast 1 upper case,atleast 1 numericvalue.
Here is a quick solution that I think is what you are looking for . . .
function validatePassword(){
var old_pass = $('#OldPassword').val();
var new_pass = $('#NewPassword').val();
var conf_pass = $('#ConfirmPassword').val();
if(old_pass === ""){
alert('Old password should not be blank.');
}
else if(new_pass === ""){
alert('New password should not be blank.');
}
else if(conf_pass === ""){
alert('Confirm password should not be blank');
}
else if(!new_pass.match(/(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{8,16}$/))
alert('New password length should be 8-16 characters,atleast 1 special character,atleast 1 upper case,atleast 1 numericvalue');
}
else if(new_pass !== conf_pass){
alert('New and confirm password should be same');
}
return false
}
This should do it. I have it on JSFiddle if you want to see it working

Why does this form submit on click of the submit button

<script type="text/javascript">
var geid = function(x) {
var element = document.getElementById(x);
return element;
}
function submitForm(){
var password = geid('password').value;
var passwordConfirm = geid('passwordConfirm');
//THIS IS OF HIGH IMPORTANCE THAT THIS CONFIRM PASSWORD MATCHES
//WILL NEED TO VALIDATE IT IN THE PHP AS WELL>
else if (password == ""){
registerMessage.innerHTML = "Please enter your Password.";
return false;
}
else if (passwordConfirm == "") {
registerMessage.innerHTML = "Please confirm your password.";
return false;
}
else if (passwordConfirm != password) {
registerMessage.innerHTML = "Your passwords don't match.";
return false;
}
else {
registerMessage.innerHTML = "Taking you to your profile, please wait a moment...";
document.forms['registerform'].submit();
}
}
<form method="post" action="register.php" id="registerform" onsubmit="return submitForm()">
<label for="password" class="registerLabel">Password</label>
<input type="password" name="password" id="password" class="registerText" /> <br />
<label for="passwordConfirm" class="registerLabel">Confirm Password</label>
<input type="password" name="passwordConfirm" id="passwordConfirm" class="registerText" /> <br />
<div class="submitMessage">
<input type="submit" id="submit" name="submit" value="Register" class="registerButton cleangray" /><br />
<div id="registerMessage"><?php echo $error ?></div>
</div>
<div class="clear"></div>
</form>
You can't start with else if; you need to start with if
if (password == ""){
registerMessage.innerHTML = "Please enter your Password.";
return false;
}
That's preventing any of your validation code from running and just submitting the form using the standard submit mechanism.
This also isn't the best way to approach the validation. Rather than return at each error, you could build up a string of messages and report them all back in one go. That way the user knows everything that's wrong — your current method will only ever set one message.
Because you have error in JavaScript, you are using else if without defining if first. Because of this error all JavaScript code fail.
Change
else if (password == ""){
to
if (password == ""){
Working demo http://jsfiddle.net/Zs3km/
BTW in your code HTML is within <script> tag, not sure if its your mistake just here. You have to close <script> tag before <form> tag is opened.

Categories

Resources