How to use jQuery Validation Plugin with textarea? - javascript

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/

Related

Trying to add hCaptcha to my site but don't understand this javascript code

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");
}
});

Stop jQuery from returning entire page into my div

So I've got a form that has the action of 'create_topic_parse.php', it sends the input values to that from 'create_topic.php', then they are inserted into the database. I am able to send any errors from the 'create_topic_parse.php' file to the 'message' div in my 'create_topic.php' page using the following code:
$("#submit").click( function() {
// I've tried e.preventDefault(); here ^ but it's giving the same result.
$.post( $("#topic_form").attr("action"),
$("#topic_form :input").serializeArray(),
function(info) {
$("#message").empty();
$("#message").html(info).css('color','#be4343');
});
$("#topic_form").submit( function() {
return false; // Not working
});
});
When the form is CORRECTLY input, and no errors are to be passed from the PHP file, the PHP script is supposed to redirect the user to 'view_topic.php?cid=".$cid."&tid=".$new_topic_id."&page=1'. If I don't include the jQuery above, this works fine.
Problem: If I include the jQuery script, it returns the entire 'view_topic.php/etcetc' page into '', which is bad.
So the question is, does anyone know how to prevent the entire page from being posted into this div, and actually redirect the user to 'view_topic.php' page when the form is correctly submitted?
Note: I've tried window.location, however I've then the issue of the concatonated variables from my PHP file that are input into the 'view_topic.php/etcetc' url. I am trying to get it to work with header('location:...'), like it does when the jQuery file isn't included.
Thanks in advance,
Richie
Solution:
jQuery + Ajax to PHP:
if($('#topic_title').val() == ''){
$('#message').html("You need to give your topic a title.");
}
Using this code I was able to check whether each data entry existed, when all of the data values were existing I'd run the AJAX script within the same file passing each value into a variable like so:
var submit = $('#submit').val();
var topic_title = $('#topic_title').val();
$.ajax({
type: "POST",
url: "create_topic_parse.php",
data: {submit:submit, topic_title:topic_title),
etc etc.
Try this one. It'll work
when form is correctly submitted then only send some string like "correct", and in jquery let you check the ouput string. if it's "correct" then redirect it to view topic via javascript.
if you want to redirect the user to an specific page sent from server, then send from server something like this in json format.
write code on server something like this.
if ($condition==true) {
$ajax_return = array(
'message' => 'correct',
'url' => 'your_redirect_url'
);
}
else
{
$ajax_return = array(
'message' => 'your user defined error message',
'url' => 'leave it blank'
);
}
$ajax_return = json_encode($ajax_return);
echo $ajax_return;
and now jquery on create_topic.php page
$("#topic_form").submit( function(e) {
e.preventDefault();
$.post(
$("#topic_form").attr("action"),
$("#topic_form :input").serializeArray(),
function(info) {
info= JSON.parse(info);
if(info.message="correct"){
window.location=info.url;
}
else{
$("#message").html('');
$("#message").html(info).css('color','#be4343');
}
});
});
I'm sure now it'll work. If not, let me know.

How to specifically validate a certain form field using Jquery Validation plugin

I'm using the Jquery Validation plugin to validate my form on the client before submitting.
There is a specific field in my form that I want to validate using ajax to the server, once the user has filled out that field (onblur).
(Basically it's the username field, I want to check on the server if the username is available and show a message accordingly)
Here is the code I'm using to validate my form:
$(document).ready(function()
{
$("#signupForm").validate({
submitHandler: ajaxSubmitForm});
});
(ajaxSubmitForm is just the js code that submits the form)
How can I use the Jquery Validation plugin to have the username field send its value to the server (using ajax) when it has changed and have the server return a result that somehow marks that field as valid on the client so the rest of the validation works?
Thanks
You can do this using the remote rule on that element. You'd apply like so:
$('#signupForm').validate({
rules: {
username: {
remote: 'check_username.php' // this is the service page that returns true/false
}
}
});
Then to trigger the validation on blur, you add the following:
$('input[name="username"]').on('blur', function() {
$('#signupForm').validate().element(this); // this triggers the single element validation
});
submitHandler won't fire until the form is submitted for the first time. If you want to check username uniqueness while the user is filling out the form for the first time, you'd need a separate function. The example below assumes you have a page that runs a SQL query to see if the provided username exists in the database, then returns a json string like "{taken:false}" if the username is unique
$('#yourForm [name="username"]').on('blur',function(){
var username = $(this).val();
$.get('check/username.php',{username:username},function(data) {
if(data.taken) {
// highlight the field and indicate that the username is already taken
}
},'json');
}
The specifics of the call to $.get would depend on how your backend is set up. But in general, the process would go:
user enters a username
user blurs out of field
$.get or $.ajax call is made to the server to check uniqueness of username
if the response from the server indicates that the username is not unique, handle your validation (higlight the field, add an X icon, etc) and either
prevent form submission until the username IS unique, or
let the form submit and return an error for duplicate username
UPDATE
If you want to create a new rule for the validation plugin, you can do something like:
function isUsernameUnique(username,field) {
var unique = false;
$.ajax({
url: 'path/to/usernameCheck/',
data: { username: username },
async: false,
success: function(data) { unique = data.unique; }
});
return unique;
}
$.validator.addMethod(
'uniqueUsername',
isUsernameUnique,
'That username is already in use. Please choose a unique username.'
);
Then, in your form's validate function:
$('#yourForm').validate({
...
rules: {
username: { uniqueUsername: true }
...
}
...
});
And, a separate blur function for your username field:
$('[name="username"]').on('blur',function(){
var unique = isUsernameUnique($(this).val(),$(this));
if(!unique) {
// handle error
}
});
This lets you reuse the same function for both your pre-submit validation and your validation plugin. However, I see two issues here:
1 - After your first submit, $.fn.validate() will eagerly validate your username field, meaning the blur event on the username field is no longer required. perhaps you can disable it after the first submit to prevent unnecessary ajax calls
2 - It's not 100% DRY, as you'll need to do your own error handling in the blur event handler

Running a script if form field validates as email

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.

Validating and Submitting a form using Javascript + Ajax

Here's what I'm trying to do.
When the 'Submit' form is clicked on my form, a javascript function will loop through all the fields of the form.
For each field a function will be called which would return true/false to indicate if it was filled in correctly or not.
If a false is returned, it shows an error message next to that field.
If all fields are correct, it submits the form. If not, it doesn't submit.
Here's the tricky part. While most of the validation is being done via javascript, the username and email need to be validated via ajax to see if the username/email is already in use or not.
The structure i'm currently using for this ajax function is something similar to this:
function validateSomething()
{
var valid;
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
return valid/
}
But that currently doesn't work.
What can I do to make it work, i.e can I stop the validateSomething() function from returning a value until its set to true/false by the inner function?
Would something like this work:
function validateSomething()
{
var valid="unset";
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
//Loop without returning until valid is set to true or false
while (valid=='unset')
{
//Do nothing?
}
return valid/
}
You can force the ajax-call to wait with async: false.
Like this using jquery:
function validateSomething() {
var valid;
$.ajax({
url: "something.php",
data: {x: y},
type: "GET",
async: false, // this makes the ajax-call blocking
dataType: 'json',
success: function (response) {
valid= response.valid;
}
});
return valid;
}
However, the big win when using AJAX is that it is asynchronous. This synchronous call might lock up the browser while it is waiting for the server.
You probably don't want to. (Or more appropriately, "Go for it, but be careful when doing so.")
Validating via AJAX is hip and slick and awesome. But it is -not- a substitute for validating server-side. And AJAx validation is -not- server-side validation. I can take the return of your function that says false and flip it to true and submit the form happily, even though you checked to make sure the username wasn't taken 'on the server'. Javascript runs on the client and can't be trusted.
Any validation you do via an AJAX call must be re-done on the server when you actually submit the form.
If you do that, then yea, AJAX validation is, again, hip and slick and awesome. So go for it. To submit a form using javascript (e.g. in the AJAX call-back handler function) you would say:
if(formwasValid)
{
document.getElementById('idOfForm').submit();
$('#idOfForm').submit(); //jQuery
}
else
{
alert('Invalid text');
}
I stopped doing extensive form validation on the client side as the code has to be duplicated on the server side anyway.
On the client-side, I just do some basic syntax checking of fields via regular expressions. These checks will be immediately triggered when the user starts typing, but they just give a visual notice as to when something went wrong (red border, different background color, a red 'X' next to the field...).
I don't prevent the user from submitting even invalid forms: Then, the server-side code with it's more detailed checks gets to work, which can easily restructure the form to separate valid from invalid fields and generate in-depth explanations as to why a check failed.

Categories