Sorry for this most likely simple question.
I am running a script on submission of the form (code below), but first I would like to validate the form (contains one text box which must be an email) before the code is executed.
The script below is taken from here to ensure the form data is passed along to the colorbox lightbox script. But i only want to run this if the form is validated. I don't know how to combine this with an email validation script. Help! At the moment i've got a script that validates email (dreamweaver's) and this running, this command still runs even if it doesn't validate and i am not sure how to edit it so it doesn't.
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:"1280", innerHeight:"884px", iframe:true, scrolling:false});
});
Then I am using this to validate the form:
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('#');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} }} else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
} if (errors) alert('The following error(s) occurred:\n'+errors);
document.MM_returnValue = (errors == '');
} }
Thanks!!!!
The HTML for the tigger is:
<input name="submit" type="image" onclick="MM_validateForm('email','','RisEmail');return document.MM_returnValue" src="images/go-button.gif" alt="Go! Get quote now!" align="top" : id="SearchButton"/>
In a nutshell: I want to tigger the code in the first snippet if the form validates using the code in the second snippet that is called by the html even in the third code snippet, but not if it doesn't.
You didn't post your HTML so I don't know if you have an actual form or just an input field without an actual form tag.
Assuming the former, you need a submit event so you can validate the form and then, if validation failed, terminate the submission.
$('#my_form').submit(function() {
//validate - forget the whole thing if it fails
if (!$('#my_field').val()) return false;
//if we get this far, validation succeeded - do other stuff now
});
A form submission is halted any time the submit callback returns false (or fires event.preventDefault()).
Andrew is correct, it would help if you provided the html in order to establish what the event trigger will be. Having reviewed the jquery plugin 'colorbox' briefly, it appears the lightbox is bound to the selectors click event.
Assuming Andrew's answer, if the email address validates you would need to manually trigger the click event for the lightbox from within the submit handler for the form. The following code should suffice.
$('#my_form').on('submit', function(e){
//perform validation.
MM_validateForm('email','','RisEmail');
//check the document variable set by the validation.
if (!document.MM_returnValue)
{
//did not validate
}else{
//open the colorbox
var search_btn = $('input#search');
search_btn.colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize();
return url + '?' + ser;
},
innerWidth: "1280",
innerHeight: "884px",
iframe:true,
scrolling:false});
//manually trigger the click event
search_btn.trigger('click');
}
//in either instance, disable the default action to ensure the form does not follow through.
e.preventDefault();
});
Obviously you'll have to replace the css selector names with your own, and utilise the email validation script that you may or may not have.
Related
Javascript isn't really my strong point. I already have the php working for the captcha on the backend but i want to be able to validate the form with JS to prevent the user from sending a form when the captcha hasn't been completed.
This is the example the hcaptca site gives:
https://medium.com/#hCaptcha/using-hcaptcha-with-php-fc31884aa9ea
And here is the JS code they give as an example.
$("form").submit(function(event) {
var hcaptchaVal = $('[name=h-captcha-response]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});
I'm not 100% sure but that appears to be Jquery and my site does not use Jquery. so i need a vanilla JS solution.
Let me try to explain:
$("form").submit(function(event) { }
// When the form is submitted
var hcaptchaVal = $('[name=h-captcha-response]').value;
// Retrieve the value of the captcha (= the value of an HTML element with the tag name="h-captcha-response"
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the Captcha");
}
// If the value of the captcha is empty, stop the form submission and alert the user
So if you are searching for a Vanilla JS solution, it's not that hard, all you have to do is convert the jQuery parts :
document.querySelector("#yourFormId").addEventListener("submit", function(event) {
var hcaptchaVal = document.querySelector('[name="h-captcha-response"]').value;
if (hcaptchaVal === "") {
event.preventDefault();
alert("Please complete the hCaptcha");
}
});
I'm working on designing a new process for internal job submission for work which now involves javascript for it to work effectively.
Scripting is not my forte but that hasn't deterred me, I've been able to find three different pieces of code to insert into the various buttons and fields and they've done what they should do. My problem is I need to combine some of these for an extra validation on submit. This is where I fall short.
The process:
There is a required field in the form which currently runs a custom validation script to check a certain format specific to the code needed for a job. This runs well and I was even able to add an alert and hint images that show when incorrect and a little tick when correct. Beautiful.
The second major part of the form is in the submit button. I hacked together a code which not only emails the submitted form with fields as the subject line but also makes all fields read only before doing so. Brilliant.
Here's the messy part. A user can enter a correct or incorrect required code and the validator does its bit but that doesn't stop them from still submitting the form. Fine. I can fix that by running the validator again on the submit button so it not only gives user feedback on blur of the required field but again validates on submit so if the field is incorrect the submit stops until the user has the correct value in the field. This is where my knowledge stops like a cliff edge and I can't seem to build a bridge.
I've tried numerous ways of calling the field value then just running the same validation script with some if and else statements but it just doesn't work.
Can anyone help? Current code for submission button below but keep in mind that the validation section of this code is also attached to the required field directly (this affects it?):
function OR_Stuff() {
var ProjectTitle = getField("ProjectTitle").value;
var Brand = getField("Brand").value;
var Name = getField("Name").value;
var Noosh = getField("INT_NooshCode").value;
for (var i = 0 ; i < this.numFields ; i++) {
var f = this.getField(this.getNthFieldName(i));
if (f.type != "Submit") // Change f.type to button name in form that the action is applied to
{
f.readonly = true;
}
}
this.mailDoc({
cTo: "email",
cBcc: "email",
cSubject: "NEW JOB: "+Brand+" - "+ProjectTitle+" - "+Noosh,
cMsg: "Thanks "+Name+" for sending through this job."
});
}
var re = /^\d{5}[A-Z]\d{2}$/
if (re.test(INT_NooshCode.value) == false) {
this.getField("RequiredAlert").display = display.visible;
this.getField("NooshTick").display = display.hidden;
app.alert("Sorry, we can't start a project without a Noosh code. \n\nPlease enter a valid Noosh code EG: 34256P02");
}
else {
OR_Stuff();
}
I am having a little bit of trouble understanding how to implement jQuery Validation Plugin. With my form that is being submitted with Ajax:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function(data) {
var like = $('.quote-wrap span iframe');
$('.inner').prepend('<div id="' + data + ' " class="quote-wrap group">' + like + '<div class="quote"><p>' + quoteVal+ '</p></div></div>');
// console.log("success");
var id = parseInt(data);
console.log(id)
// some code after being successfully sent
});
After adding validation plugin, how would I set the defaults and make sure it's what I want the form to do?
It's just a textarea, that a user submits a simple quote. (text and numbers) and shouldn't submit anything else. Right now I can submit HTML, or anything else I like.
What do I need to do to make sure the user can't?
I have tried:
If all you need to do is make sure users can't post HTML, then check out this article on StackOverflow: HTML-encoding lost when attribute read from input field.
Otherwise, you can use jQuery Validation to perform a similar method during validation.
try this
$("#myform").validate();
$("a.check").click(function () {
if ($("#myform").valid()) {
//if valid do form submit
}
else {
return false;
}
});
you can check the validity of the form . if valid do your work . else return false,
check this
http://docs.jquery.com/Plugins/Validation/valid
and one more thing, you are using submit event of the form. that causes page refresh. so you have to
return false OR use http://api.jquery.com/event.preventDefault/
Since there is no minlength="" for input, how can I make an if statement that does the following:
If the user has not input more than 3 characters it will not be saved in a database.
Here is the input:
QTY<input title="QUANTITY PER ITEM" size="1" name="inputQTY" value="**(minimun of 3 characters)**"/>
any ideas??
Note: it doesn't matter if there's a min value restriction on the input field or not; a user can still spoof the form to contain whatever value he or she wants. Thus, you need to validate on the server side.
Let's say you're using PHP as your server side language.
$inputQTY = $_POST['inputQTY'];
if (strlen($inputQTY) < 3) {
// DO NOT INSERT INTO DB
}
else {
// insert after further scrubbing input
}
Read this: What's the best method for sanitizing user input with PHP?
Form validation is the process of checking if the form fields are filled in correct formats if they are processes. In your question, the correct format is "more than 3 characters". Of course, if statements are involved during form validations. In the client-side, you use JavaScript code to validate form fields.
Here is how it works: A form has an onsubmit event handler, when the user clicks Submit, or presses Enter, onsubmit will be triggered. onsubmit is where you put the form validation code.
<script>
function onsubmit() {
if (document.forms.mainForm.inputQTY.value.length < 3) {
alert("ERROR: Must be more than 3 characters");
return false; // stops the form submission
}
return true;
}
</script>
And here is how you add the onsubmit handler
...
The onsubmit function can return a value: true to let the form to be submitted, or false to stop the submission.
What is document.forms.mainForm.inputQTY.value.length? document.forms.mainForm references to the form named mainForm, while .inputQTY finds the inputQTY field.
You can use document.getElementsByTagName to manually find these elements, but it is [time and space]-consuming to write that type of code.
Because some users have JavaScript disabled, or crackers intentionally disable JS to bypass validation, you must validate server-side.
Server-side code will be something like this:
if (strlen($_GET['inputQTY']) < 3) {
echo "ERROR: Must be more than 3 characters";
} else {
// submit data
}
NOTE: code written from head, not tested
Im attempting to modify a JAvascript login form. The form action calls a DLL so I cant modify it to include the modifications I want to make.
Here is the javascript function Im using:
function SubmitForm() {
var Domain = "#domain.com"
var txtBox = document.getElementById('username');
if(txtBox.value.indexOf("\\") != -1){
return;
}
if((txtBox.value.indexOf("#") == -1) && (txtBox.value != "")) {
txtBox.value += Domain;
return;
}
}
Basically checks the username for \ and # chars first, if it doesnt contain those values it adds the Domain to the username.
Ive added this to the <form> onsubmit="return(SubmitForm());" to calls and use this function. However I dont want the user to see the domain been added to the username.
Is there any other way to do this>
Don't modify the input box, then. Rather have the onSubmit handler write whatever you want into a type="hidden" field which is used instead.
If you absolutely can't change this on the server side, you could always change the ID of your username input field, and create a hidden field with an ID of username that you can populate with the user's input plus your domain.