I have a form set up with the jQuery Validation plugin.
see here: http://jsfiddle.net/9q865xof/
And I have this (non-jquery) javascript function from how my form was validated before adding the plugin.
function busregform(form, password) {
// new input for hashed password
var p = document.createElement("input");
// create element
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// clear plaintext password
password.value = "";
// submit the form
form.submit();
return true;
}
With the hex_sha512() function in its own file too.
The idea here is to post the password from the form through busregform() to create a hashed password to then post for my PHP script to process.
I have tried adding this to my validation jquery code:
submitHandler: function(){
var pw = $("#pass").val();
var form = $("#business-reg-form");
busregform(form,pw);
}
With no luck... Not sure what to do now. I'm thinking I should use ajax?
How can I call busregform() when the plugin-validated form is submitted?
The busregform method is expecting a dom element reference for form so you need
$('#business-reg-form').validate({
rules: {
address: {
required: true,
minlength: 6
},
email: {
required: true,
email: true,
minlength: 6
},
company: {
required: true
},
pass: {
required: true,
minlength: 6
},
confirmpw: {
required: true,
minlength: 6,
equalTo: "#pass"
}
},
submitHandler: function() {
var pw = $("#pass");
var form = $("#business-reg-form");
//pass the dom element reference
busregform(form[0], pw[0]);
return false;
}
});
function busregform(form, password) {
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
return true;
}
if (!window.hex_sha512) {
//stub method
window.hex_sha512 = function(value) {
return 'hex_sha512-' + value;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<form method="post" name="business_regform" id="business-reg-form" action="">
<p>
<input type="text" name="company" id="company" placeholder="company name" required />
</p>
<p>
<input type="text" name="address" id="address" placeholder="address" required />
</p>
<p>
<input type="text" name="email" id="email" placeholder="email" required />
</p>
<p>
<input type="text" name="pass" id="pass" placeholder="password" required />
</p>
<p>
<input type="text" name="confirmpw" id="confirmpw" placeholder="confirm password" required />
</p>
<p>
<input type="submit" class="btn" id="business-reg-submit" value="submit" />
</p>
</form>
Demo: Fiddle - You can inspect the request using the network tab to see the hashed password
Related
I am trying to make a validation page and I need to stop saying "Please fill in the form" when text is entered in the text box. I only needed to validate when the text boxes are empty
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" onsubmit="return validation();" enctype="text/plain">
Name:
<input type="text" name="name" id="name" /><br />
Surname:
<input type="text" name="surname" id="surname" /><br />
Email:
<input type="email" name="email" id="email" /><br />
Message:
<textarea name="Message" maxlength="3500"></textarea><br />
<button id="submit" onclick="validation()">Submit</button>
</form>
<script>
var name = $("#name").value;
var surname = $("#surname").value;
var email = $("#email").value;
var comments = $("#comments").value;
function validation() {
if (name == "" || surname == "" || email == "" || comments == "") {
document.myForm.name.setCustomValidity("Please fill out this field");
document.myForm.surname.setCustomValidity("Please fill out this field");
document.myForm.email.setCustomValidity("Please fill out this field");
document.myForm.comments.setCustomValidity("Please fill out this field");
} else {
document.myForm.name.setCustomValidity();
document.myForm.surname.setCustomValidity();
document.myForm.email.setCustomValidity();
document.myForm.comments.setCustomValidity();
}
}
</script>
your code is showing an error because in your last line you are using "comments" instead of "Message", also setCustomValidity() takes a string with the error message or an empty string and for it to work well consider using the document's methods for retrieving elements, in addition you will need to add reportValidity() so your code should look like this
if (name == "" || surname == "" || email == "" || comments == "") {
name=document.getElementById('name')
name.setCustomValidity("Please fill out this field");
name.reportValidity()
}
else
name.setCustomValidity('');
name.reportValidity()
also you can consider using a helper function to use the element id dynamically
Update:
you can use this it will work
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="mailto:kyletab03#gmail.com" name="myForm" method="post" id='myform' enctype="text/plain">
Name:
<input type="text" name="name" id="name" required="required"/><br />
Surname:
<input type="text" name="surname" id="surname" required="required" /><br />
Email:
<input type="email" name="email" id="email" required="required" /><br />
Message:
<textarea name="Message" id="message" maxlength="3500" required="required"></textarea><br />
<button onlclick='validation()'>Submit</button>
</form>
<script>
function validate(inputID)
{
var input = document.getElementById(inputID);
var validityState_object = input.validity;
if (validityState_object.valueMissing)
{
input.setCustomValidity('Please fill out this field');
input.reportValidity();
}
else
{
input.setCustomValidity('');
input.reportValidity();
}
}
function validation() {
var name= document.getElementById('name').value
var surname=document.getElementById('surname').value
var email=document.getElementById('email').value
var message=document.getElementById('message').value
validate('name')
validate('surname')
validate('email')
validate('message')
if (name!=''&&surname!=''&&email!=''&&message!='') {
$('#myform').submit();
}
}
</script>
The easiest way to validate forms with jquery is to use jquery validate.
I would definately advise you NOT to use mailto directly in your form post url simply because spam bots and things like that may catch hold of your form and try to use it to send spam mail. i add jquery validation and captcha on all of the contact us pages that i create for clients.
$('#frmsendemail').validate({ // Send Email Form
ignore: '.ignore',
rules: {
seFullname: {
required: true,
minlength: 2
},
seContact: {
required: true,
phonesUK: true,
},
seMail: {
required: true,
email: true
},
seMsg: {
required: true
},
seCaptchaStatus: {
required: function () {
// verify the user response
var thisresponse = grecaptcha.getResponse(seCaptcha);
if (thisresponse == "") {
return true;
} else {
return false;
}
}
}
},
messages: {
seFullname: {
required: "Please Enter Your Name",
minlength: jQuery.validator.format("Please ensure you enter a name more than {0} characters long.")
},
seContact: {
required: "Please Enter a contact number",
phonesUK: "Your Contact Numer should be in the format of: 07123 456 789 or 0123 123 4567",
minlength: jQuery.validator.format("Your contact number should me at least {0} numbers.")
},
seMail: {
required: "Please Enter Your Email Address",
email: "Your email address should be in the format of "username#domain.com""
},
seMsg: "Please Enter A Message",
seCaptchaStatus: "Please complete reCaptcha."
},
highlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-success icon-valid').addClass('border-error icon-invalid');
$(id_attr).removeClass('glyphicon-ok icon-valid').addClass('glyphicon-remove icon-invalid');
},
unhighlight: function (element) {
var id_attr = "#" + $(element).attr("id");
$(element).closest('.pure-form-control-group').removeClass('border-danger icon-valid').addClass('border-success icon-valid');
$(id_attr).removeClass('glyphicon-remove icon-invalid').addClass('glyphicon-ok icon-valid');
},
showErrors: function (errorMap, errorList) {
$(".seerrors").html('<h6><i class="fa fa-exclamation-circle"></i> Your form contains ' +
this.numberOfInvalids() +
' errors, see details below.</h6');
this.defaultShowErrors();
},
validClass: "border-success",
invalidClass: "border-danger",
errorClass: "border-danger",
errorElement: 'div',
errorLabelContainer: ".seerrors",
submitHandler: function () {
//Now that all validation is satified we can send the form to the mail script.
//Using AJAX we can send the form, get email sent and get a response and display a nice
//message to the user saying thank you.
//For Debugging
//console.log("Sending Form");
$.post("../php/sendemail.php", $('#frmsendemail').serialize(), function (result) {
//do stuff with returned data here
//result = $.parseJSON(result);
console.log(result.Status);
if (result.Status == "Error") {
//Create message from returned data.
//This helps the user see what went wrong.
//If its a form error they can correct it,
//if not then they can see whats wrong and alert us.
var message3 = '<p style="font-size:10pt;text-align:left !important;">We encountered an error while processing the information you requested to send.</p><p style="font-size:10px;text-align:left;">We appologise for this, details of the error are included below.<p><hr><p style="text-align:left;font-size:10px;">Error Details:' + result.Reason.toString() + '</p><pstyle="text-align:left;font-size:10px;">If this error persists, please email enquiries#cadsolutions.wales</p>';
// Show JConfirm Dialog with error.
$.confirm({
title: '<h2 style="text-align:left"><i class="fa fa-exclamation-circle"></i> We encountered an error<h2>',
content: message3,
type: 'red',
// Set Theme for the popup
theme: 'Material',
typeAnimated: true,
buttons: {
close: function () {}
}
});
The above code is from a page that i created for a contact us script. the script sets all the inputs that are on the page using the name= attribute and then sets messages for the inputs when validation rules are not met, highlights and un-highlights the fields with errors, shows error messages in a set div tag and then handles form submit when the form is valid. :)
I have a form in html which I want to run verification in Javascript first before POST ing to PHP. However the link up to the PHP section does not seem to be working despite the fact that I have assigned names to each input tag and specified an action attribute in the form tag.
Here is the HTML code for the form:
<form id="signupform" action="signupform.php" method="post">
<input type="text" name="Email" placeholder="Email Address" class="signupinput" id="email" />
<br />
<input type="password" name="Password" placeholder="Password" class="signupinput" id="passwordone" />
<br />
<input type="password" placeholder="Repeat Password" class="signupinput" id="passwordtwo" />
<br />
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="submit" />
</form>
The button calls the javascript function which I use to verify the values of my form before sending to php:
function verifypass() {
var form = document.getElementById("signupform");
var email = document.getElementById("email").value;
var password1 = document.getElementById("passwordone").value;
var password2 = document.getElementById("passwordtwo").value;
var emailcode = /^(([^<>()\[\]\\.,;:\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 (emailcode.test(email)) {
if (password1.length > 6) {
if (password1 == password2) {
form.submit(); //this statement does not execute
} else {
$("#passwordone").notify("Passwords do not match!", {
position: "right"
})
}
} else {
$("#passwordone").notify("Password is too short!", {
position: "right"
})
}
} else {
$("#email").notify("The email address you have entered is invalid.", {
position: "right"
})
}
}
For some reason, some JavaScript implementations mix up HTML element IDs and code. If you use a different ID for your submit button it will work (id="somethingelse" instead of id="submit"):
<input type="button" value="Sign Up" class="signupinput" onClick="verifypass()" id="somethingelse" />
(I think id="submit" has the effect that the submit method is overwritten on the form node, using the button node. I never figured out why, perhaps to allow shortcuts like form.buttonid.value etc. I just avoid using possible method names as IDs.)
I'm not sure why that's not working, but you get around having to call form.submit(); if you use a <input type="submit"/> instead of <input type="button"/> and then use the onsubmit event instead of onclick. That way, IIRC, all you have to do is return true or false.
I think it would be better if you do it real time, for send error when the user leave each input. For example, there is an input, where you set the email address. When the onfocusout event occured in Javascript you can add an eventlistener which is call a checker function to the email input.
There is a quick example for handling form inputs. (Code below)
It is not protect you against the serious attacks, because in a perfect system you have to check on the both side.
Description for the Javascript example:
There is two input email, and password and there is a hidden button which is shown if everything is correct.
The email check and the password check functions are checking the input field values and if it isn't 3 mark length then show error for user.
The showIt funciton get a boolean if it is true it show the button to submit.
The last function is iterate through the fields object where we store the input fields status, and if there is a false it return false else its true. This is the boolean what the showIt function get.
Hope it is understandable.
<style>
#send {
display: none;
}
</style>
<form>
<input type="text" id="email"/>
<input type="password" id="password"/>
<button id="send" type="submit">Send</button>
</form>
<div id="error"></div>
<script>
var fields = {
email: false,
password: false
};
var email = document.getElementById("email");
email.addEventListener("focusout", emailCheck, false);
var password = document.getElementById("password");
password.addEventListener("focusout", passwordCheck, false);
function emailCheck(){
if(email.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Email";
fields.email = false;
} else {
fields.email = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log("asdasd"+show);
showIt(show);
}
function passwordCheck(){
if(password.value.length < 3) {
document.getElementById("error").innerHTML = "Bad Password";
fields.password = false;
} else {
fields.password = true;
document.getElementById("error").innerHTML = "";
}
show = checkFields();
console.log(show);
showIt(show);
}
function showIt(show) {
if (show) {
document.getElementById("send").style.display = "block";
} else {
document.getElementById("send").style.display = "none";
}
}
function checkFields(){
isFalse = Object.keys(fields).map(function(objectKey, index) {
if (fields[objectKey] === false) {
return false;
}
});
console.log(isFalse);
if (isFalse.indexOf(false) >= 0) {
return false;
}
return true;
}
</script>
I am using an onSubmit() function to validate form entries.
The form and validation function work OK,if the form is in a standalone php file or an html file.
But when the form is embedded in a Bootstrap modal the JS validation function throws an error message. [object HTMLInputElement]
I have tried changing document.getElementById('uemail') to document.getElementById('uemail').value as recommended in another answer,
but no value has apparently been passed to the function.
If I remove the onSubmit() attribute then the values are passed correctly to the action script on the server.
This must be common usage. What am I doing wrong?
This is an abbreviated section of my code:
<script>
function formCheck() {
var valid = true;
//alert('in function');
var email = document.getElementById('uemail');
alert('email:' + email);
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
valid = false;
}
return valid;
}
</script>
<form id="regform" action="action.php" method="post" onSubmit="return formCheck()">
Email: <input type="text" name="uemail" id="uemail" size="50" value="" required><span id ="ast">*</span><br>
<input type="submit" name="Submit" value="Register" />
</form>
EDIT: looks like you can't do document.getElementById, you can do this instead:
function formCheck(formEl) {
//...
var email = formEl.getElementsByTagName("input")[0].value;
// this will get the first input-element in your form
and
onsubmit="return formCheck(this)"
Mistake: The variable email you are testing is a HTMLElement, not a string:
Solution: set email to the value of the HTMLInputElement:
var email = document.getElementById('uemail').value;
also email.focus; is not doing anything, use email.focus();
Demo:
function formCheck() {
var valid = true;
//alert('in function');
var email = document.getElementById('uemail').value;
alert('email:' + email);
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email)) {
alert('Please provide a valid email address');
email.focus;
valid = false;
}
return valid;
}
<form id="regform" action="action.php" method="post" onsubmit="alert(formCheck())">
Email:
<input type="text" name="uemail" id="uemail" size="50" value="" required><span id="ast">*</span>
<br>
<input type="submit" name="Submit" value="Register" />
</form>
I have the following html form:
<form class="center" id="myform">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
<div class="terms">
<input type="checkbox" class="required" value="None" id="terms" name="terms">I accept terms</input>
</div>
</p>
<input type="submit" id="sendfeedback" value="now" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" id="postmelater" value="send" disabled/>
</form>
And as you can see above, I have a form with two buttons. The logic behind it works like that, that when I want to put text to database with current timestamp - I choose button sendfeedback. However, there's also a possibility of adding the feedback with chosen timestamp, that is happening when user choses the date from datetimepicker and hits postmelater. Now, the ajax code for that looks like this:
$(document).ready(function () {
$('#myform').validate({// initialize the plugin
errorElement: 'div',
rules: {
email: {
required: true,
email: true
},
slogan: {
required: true,
minlength: 2
},
terms: {
required: true,
maxlength: 2
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
});
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
});
There's a validation process attached to the fields and so far - only support for the first button. How can I add a support for 2nd button, and in case when user clicks it - also pass the datetime attribute to ajax? Can I distinguish them somehow in Ajax? Thanks!
Here depends on functionality of validation plugin, when it reacts, but likely you can try to add onclick to buttons which sets some hidden variable, indicating which button was pushed. Like this:
<input type="submit" id="sendfeedback" onclick="this.form.clickedbtn.value=1" value="now" disabled/>
<input type="submit" id="postmelater" value="send" onclick="this.form.clickedbtn.value=2" disabled/>
and also add hidden input to the form like this
<input type="hidden" id="clickedbtn" name="clickedbtn">
Than in the handler add
var clickedbtn = $("#textarea").val();
...
clickedbtn: clickedbtn,
so form will look like this:
<form class="center" id="myform">
<input type="hidden" id="clickedbtn" name="clickedbtn">
<p>
<input id="email" name="email" type="email" class="textox email" title="" placeholder="your#email.com" required>
</p>
<textarea name="slogan" id="textarea" maxlength="140" style="resize:none" class="textoxarea" title="Please enter at least 5 characters" placeholder="Placeholder" ></textarea>
I accept terms
</p>
<input type="submit" id="sendfeedback" value="now" onclick="this.form.clickedbtn.value=1" disabled/>
<input id="datetimepicker" type="text" readonly="readonly">
<input type="submit" onclick="this.form.clickedbtn.value=2" id="postmelater" value="send" disabled/>
</form>
And handler will look like this:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
var date = 0;
var stand = 1;
var clickedbtn = $("#textarea").val();
$.ajax({
url: 'savedatanow.php'
type: "POST",
data: {
mail: mail,
text: text,
date: date,
clickedbtn: clickedbtn,
stand: stand
},
success: function(response)
{
alert(response);
}
});
}
After that in php script you can check
if ($_POST["clickedbtn"]==1) {
send now code
} else {
other code
}
Change
$('#myform').find('input, textarea').on('change', function () {
var btn = $('#myform').find('input[type=submit]');
if ($('#myform').valid()) {
btn.removeAttr('disabled');
} else {
btn.attr('disabled', 'disabled');
}
});
to
$('#myform').find('input, textarea').on('change', function () {
var sendfeedbackbtn = $('#sendfeedback');
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
if ($('#myform').valid()) {
sendfeedbackbtn.removeAttr('disabled');
datepicker.removeAttr('readonly');
if (isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
}
} else {
datepicker.attr('readonly', 'readonly');
sendfeedbackbtn.attr('disabled', 'disabled');
postmelaterbtn.attr('disabled', 'disabled');
}
});
So it enables the sendfeedback and the timestamp input area. And if not valid, all button and timestamp area will be disabled.
Then add
$('#myform').find('#datetimepicker').on('change', function () {
var postmelaterbtn = $('#postmelater');
var datepicker = $('#datetimepicker');
// Need to implement isTimeValid method.
if ($('#myform').valid() && isTimeValid()) {
postmelaterbtn.removeAttr('disabled');
} else {
postmelaterbtn.attr('disabled', 'disabled');
}
});
So when the timestamp area is changed, check if its valid (need implement isTimeValid), and decide whether to make postmelater able to clicked or not.
And your submit handler should be:
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
var mail = $("#email").val(); //mg
var text = $("#textarea").val();
// Decide to send a timestamp data or not.
var timestamp = $('#datetimepicker').attr('readonly') ? null : $('#datetimepicker').val();
var date = 0;
var stand = 1;
$.ajax({
url: 'savedatanow.php',
type: "POST",
data: {
mail: mail,
text: text,
date: date,
stand: stand
// So this value will be null or whatever your input
timestamp: timestamp
},
success: function(response)
{
alert(response);
}
});
}
And you can decide PHP side's behavior on whether the given timestamp is a null value or not.
As you give all these inputs an id, I directly use its id selector to get them, but you can still change to other selector at wish.
You could use js/php to set the default value of your date field to be current date. That way you would only need one submit button:
<input type="date" value="<?php echo date("Y-m-d")?>">
or
<input type="date" id="datefield">
<script>
document.getElementById("datefield").value = new Date().getFullYear()+"-"+("0"+(new Date().getMonth()+1)).slice(-2)+"-"+("0" + new Date().getDate()).slice(-2);
</script>
But if you absolutely want to have two buttons, you could do:
<input type="button" onClick="firstButton()">
<input type="button" onClick="secondButton()">
and
function firstButton(){
//do what you need to
document.getElementsByTagName("form")[0].submit();
}
...and same for button two.
I am working with Parse for Javascript, and below is my dilema:
During the signup process, along with the username, and password, the first and last name of the user would have to recorded into parse. As of now, only the username and password is stored.
Below is the javascript signup function code:
SignUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
var first_name = this.$("#fname").val();
var last_name = this.$("#lname").val();
Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
success: function(user) {
user.set("first_name", first_name);
user.set("last_name", last_name);
new ManageTodosView();
self.undelegateEvents();
delete self;
},
Below is the html form code (ask user to enter their information):
<form class="signup-form">
<h2>Sign Up</h2>
<div class="error" style="display:none"></div>
<input type="text" id="fname" placeholder="Please enter your First Name" />
<input type="text" id="lname" placeholder="Please enter your Last Name" />
<input type="email" id="signup-username" placeholder="Please enter your email" />
<input type="password" id="signup-password" placeholder="Create a Password" />
<button>Sign Up</button>
</form>
Any help would be greatly appreciated.
User.set won't save the changes you will need to call save once you set the first name and last name. Also you don't need to do this after calling signing up. Try the code below it should work.
SignUp: function(e) {
var self = this;
var username = this.$("#signup-username").val();
var password = this.$("#signup-password").val();
var first_name = this.$("#fname").val();
var last_name = this.$("#lname").val();
var user = new Parse.User();
user.set("username", username);
user.set("password", password);
user.set("first_name", first_name);
user.set("last_name", last_name);
user.signUp(null, {
success: function(user) {
new ManageTodosView();
self.undelegateEvents();
delete self;
}
}