I’m trying to validate a PromoCode prior to form submission. I AM able to do that but if the result is false, I am unable to submit the form unless the input field has been cleared. I’m a self-taught hobby coder and don’t really understand JS, AJAX or cfcomponent (this is my first shot at all of it.) I’ve had a great deal of help getting to this point. All additional help is greatly appreciated.
SUMMARY:
If the PromoCode the user types into the text field matches what’s stored in the DB… all is good. They submit the form and get the discount.
If the PromoCode the user types into the text field does NOT match, they get the message “Sorry, that is not a valid promo code” but cannot submit the form unless the text field has been cleared.
I need the user to be able to submit the form if the PromoCode is invalid… they just wouldn’t get the discount. We just told them it was invalid so they’re on their own. I'd hate to have the user not understand this and leave the site frustrated without registering.
JAVASCRIPT
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
promocode: {
remote: {
url: "/components/promoCodeComponent.cfc?method=validatePromoCode",
data: {
courseId : $("#courseId").val()
}
}
}
},
messages: {
promocode: {
remote: jQuery.validator.format("Sorry, {0} is not a valid Promo Code")
}
},
errorClass: "text-danger",
validClass: "text-success"
});
});
FORM
<form id="signupform" autocomplete="off" method="get" action="">
<!--- demo only --->
Course Id: <input id="courseId" name="courseId" type="text" value=""><br>
Promo Code: <input id="promocode" name="promocode" type="text" value=""><br>
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</form>
CFC
component {
// Note: See Application.cfc docs on setting application level datasource, i.e. "this.datasource"
remote boolean function validatePromoCode(string courseId, string promoCode) returnFormat="json"{
local.qPromoCode = queryExecute(
" SELECT COUNT(*) AS TotalFound
FROM Courses
WHERE Id = :courseId
AND PromoCode = :promoCode
AND LEN(PromoCode) > 0
"
, {
promoCode = { value=arguments.promoCode, cfsqltype="varchar" }
, courseId = { value=arguments.courseId, cfsqltype="integer", null=!isNumeric(arguments.courseId) }
}
, { datasource=“My_DataSource_Name" }
);
;
if (local.qPromoCode.TotalFound gt 0) {
return true;
}
return false;
}
}
Related
Good Evening,
I am trying to create a simple JavaScript login form that will validate by checking only 1 specific email address which has been declared and 1 password that has been declared.
However, no matter what is typed into the fields, even if nothing is present, once the submit button is clicked, the user is directed to the desired page.
I need it to only allow the desired page if the email address and password are the correct. Otherwise, notify them that it is incorrect.
Here is a link to [codepen][1] so you can see the page and script.
https://codepen.io/m0rrisim0/pen/bmzyqj
Any help is appreciated in figuring out why the script is not validating.
You have to use the attribute value from document.getElementById method,
like the following example: document.getElementById("UserName").value
function validate() {
'use strict';
var UserName = document.getElementById('UserName').value;
var email = "adrian#tissue.com";
var Password = document.getElementById('Password').value;
var pass = "welcome1";
if ((UserName == email) && (Password == pass)) {
return true;
} else {
alert("UserName and/or Password Do Not Match");
return false;
}
}
Your form's inputs lack the id atrribute and should return the function on submit event.
<form action="Issues.html" method="post" id="loginform" onsubmit="return validate()">
UserName:
<input type="text" name="UserName" id="UserName">
<br>
<br>
Password:
<input type="password" name="Password" id="Password">
<hr>
<input type="submit" value="Submit">
</form>
Your problem was getElementById(), this function requires a argument and cause a error. Because of this error the line loginform.onsubmit = validate; was never reached so the submit button submit the form without calling a validate function.
There is no need to put this line inside the if statement, but if you want you can change a little bit to getElementById without the parentesis, this way it evaluates to a function that in js is truthy.
You can check a working version of you code here:
if (document && document.getElementById) {
var loginform = document.getElementById('loginform');
loginform.onsubmit = validate;
}
https://codepen.io/francispires/pen/mzvYKX
You can improve this validation
I am using this Bootstrap validator github.com/1000hz/bootstrap-validator for my bootstrap forms but it appears there is no way to set some external JS conditional before submitting forms.
For example, I would like to do the following from an external JS files:
1 # if form or some input of the form is invalid using validator() then I do some action.
2 # else Users will see some bootstrap button loading message until everything is submitted into the databases.
You can have a single case here:
$('button[data-loading-text]').click(function () {
var btn = $(this);
btn.button('loading');
$.blockUI();
// #1 if form is invalid using validator() then I unblock the please wait message $.unblockUI(); and reset the bootstrap loading button.
// #2 else users will still see the "please wait" message + bootsrap loading button untill everything is submitted into the databases.
});
http://jsfiddle.net/temgo/k07nx06k/12/
Any help will be appreciated as it appears the plugin events are only set for specific field not for full form validation.
Regards
Check out the Events section on 1000hz page. (http://1000hz.github.io/bootstrap-validator/#validator-events)
If you want to fire up the action before validating - just listen to the event.
$('#someFormId').on('validate.bs.validator', function(){
doSomeStuff();
});
Edit
The problem with events is that it is fired after every field. From what I know this plugin doesn't provide an event for finished successful validation.
For your ref hope it will help u
$(document).ready(function () {
$('#contact-form').validate({
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
message: {
minlength: 2,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('Done');
}
});
});
I came across this question looking for something else, but I have worked on precisely what you're trying to achieve.
My solution was to use the snippet of code the plugin author gives for binding to the submit button
$('#form').validator().on('submit', function (e) {
if ( !e.isDefaultPrevented() ) {
// put your conditional handling here. return true if you want to submit
// return false if you do not want the form to submit
}
});
Hope that helps someone out.
$(function () {
$("#myForm").validator();
$("#myButton").click(function (e) {
var validator = $("#myForm").data("bs.validator");
validator.validate();
if (!validator.hasErrors())
{
$("myForm").submit();
} else
{
...
}
}
})
Hope with will help.
I am working so much for a better coding with this form validator js plugin.
Follow my code and try yourself:
// Select every button with type submit under a form with data-toggle validator
$('form[data-toggle="validator"] button[type="submit"]').click(function(e) {
// Select the form that has this button
var form = $(this).closest('form');
// Verify if the form is validated
if (!form.data("bs.validator").validate().hasErrors()) {
e.preventDefault();
// Here go the trick! Fire a custom event to the form
form.trigger('submitted');
} else {
console.log('Form still not valid');
}
});
// And in your separated script, do the following:
$('#contactForm').on('submitted', function() {
// do anything here...
})
Consider the following HTML code:
<form id="contactForm" action="/contact/send" method="POST" data-toggle="validator" role="form">
<div class="form-group has-feedback">
<label for="inputName" class="control-label">Name:</label>
<input type="text" name="inputName" id="inputName" class="form-control" data-error="Your input has an invalid value"/>
<span class="help-block with-errors"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Send</button>
</div>
</form>
you can use validated.bs.validator to hand the event in order to do something after validating the form.
Regards!
I switched from type=click to type=submit so that I can use the Enter key to login. The if/else statements for invalid username/password functions fine. But if I input the correct credentials it wont load the location(different HTML page.)
PS: I'm new to coding in general(only 3 weeks in) Try to explain it so a newbie would know.
Thanks in advance.
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
location="Random.html"
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
}
</script>
<form name=login onsubmit="check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
You need to use .href on location
location.href = "Random.html";
(Also, since you said you were new, be sure to keep your dev console (F12) open when writing JavaScript and testing - you'll catch a lot of errors very early on)
Two things:
1 - Proper way to simulate a clink on a link is to use change the href attribute of location, not location itself. The line below should work:
window.location.href = "Random.html";
2 - As you are redirecting to another page, you have to "suppress" (stop) the natural onsubmit event.
In other words, you have to return false on the onsubmit event, otherwise the redirection (to Random.html) won't have a chance to work because the submit event will kick in (and sedn the user to the action page of the form) before the redirection works.
So change <form name=login onsubmit="check_info()"> to:
<form name=login onsubmit="return check_info()">
And add a return false; to the end of check_info().
The full code should be as follows:
<script type="text/javascript">
function check_info(){
var username = document.login.username.value;
var password = document.login.password.value;
if (username=="" || password=="") {
alert("Please fill in all fields")
} else {
if(username=="test") {
if (password=="test") {
window.location.href = "Random.html"; // ------ CHANGED THIS LINE
} else {
alert("Invalid Password")
}
} else {
alert("Invalid Username")
}
}
return false; // ------------------------ ADDED THIS LINE
}
</script>
And the HTML (only the onsubmit changed):
<form name="login" onsubmit="return check_info()">
Username:
<input type="text" name="username" id="username"/>
<br>
Password:
<input type="password" name="password" id="password"/>
<br>
<br>
<input type="submit" value="Login"/>
</form>
JSFiddle demo here.
The new way of doing this - set a breakpoint at the line
if(username=="test") {
And step through it to find what the problem is.
The old school way of doing this (from back before we had Javascript debuggers) is to alert messages in each of those blocks, and figure out why you step into that block to begin with. It's a lot more cumbersome than the debugger, but sometimes you may need to resort to old school hacks.
JavaScript code of validation- https://freedigitalphotos.net/images/js/judd-validate.js
We have some new forms on our website which have client side JavaScript validation.
The validation is triggered when the user "defocuses" from the form fields. The validation is a combination of AJAX (checking database for valid user names etc) and JavaScript (checking fields not blank, or contain expected data).
The user has to click the form submit button twice to send the form. It seems that the first click is triggering the field validation but not submitting the form. Clicking for a second time successfully completes the form.
Go to- https://freedigitalphotos.net/images/recover_password.php
Type arifkpi#gmail.com in the email field, and then immediately hit submit. Again, notice that the first click merely validates the input, using AJAX it is checking the email address is in the database. A second click is required.
I want to fix this, so everything will work with a single click.
Instead of calling Ajax validations on focustout event, you can call it on click of your button and if Ajax returns true result then submit form programatically. Refer few sample code lines:
Html Part:
<form method="post" id="registration_form" name="registration_form" action="register.php">
EmailId: <input type="text" id="email_id" name="email_id">
<label class="error" for="username" id="globalErrorUsername"></label>
Username: <input type="text" id="username" name="username">
<label class="error" id="globalErrorEmail"></label>
<button type="button" id="register_btn" name="register_btn">Register</button>
</form>
Js Part:
$("#register_btn").click(function() {
//.valid function is useful when you are using jquery Validate library for other field validation
if ($('#registration_form').valid()) {
var email_id = $('#registration_form').find('#email_id').val(),
username = $('#registration_form').find('#username').val();
$.ajax({
beforeSend: function() {
$('#globalErrorUsername').html('');
$('#globalErrorEmail').html('');
}, //Show spinner
complete: function() { },
type : 'post',
url : 'check-user-existence.php',
dataType :'json',
data : 'email_id=' + email_id + '&username=' + username,
success:function(response) {
if(response.success == 1) {
//submit the form here
$("#registration_form").submit();
} else if (response.error == 1) {
if(response.details.username != undefined) {
$('#globalErrorUsername').show();
$('#globalErrorUsername').html(response.details.username);
}
if(response.details.email_id != undefined) {
$('#globalErrorEmail').show();
$('#globalErrorEmail').html(response.details.email_id);
$('#email_id').focus();
} else {
$('#username').focus();
}
}
}
});
} else {
return false;
}
return false;
});
<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)