Why does .match() stop my code from executing? - javascript

I'm having trouble with a form I'm trying to validate. I'm trying to make sure for the email input that the email is the correct format, and if it is not I'll be able to send an error message to the user. Unfortunately, I can't get the return false; to execute.
Here is my current code:
function validate(){
var email = $('input.email').value;
var emailRE = /^.*#.+\..{2,5}$/;
if (email.match(emailRE)){
alert("This is true");
} else {
alert("This isn't true.");
}
return false;
}
When I execute this, the page reloads and the form submits, and neither alert goes off. However, when I take out the whole if, else section, the return false; executes, and the page doesn't reload. I also tried taking out just the '.match()', and the code executed fine. So what is wrong with the .match() part that's causing it to fail?
Any help is extremely appreciated. Thank you!

You have to use $('input.email').val() instead of $('input.email').value
http://jsfiddle.net/bMJH2/6/
value is for the DOM object. But the object you are dealing with is a jQuery object, so the proper way is to use val(). If you run it in Firefox/Firebug using value, it will show the error:
email is undefined
[Break On This Error] if (email.match(emailRE)){

Related

Alert in Pug(Jade) after retrieving a value from the node server

I want to implement an alert when the page loads under an expecific circunstance ,retrieving the value from an Node server when the user or passwowrd are wrong.
But it just doesnt do anything. I had tested it and yes, ErrorCon(the variable i get from my Node server) get its expected value when the circunstance appear so the node part shouldnt be the problem
This is the code i am trying to apply, right in the body:
script.
(function (){
function init(){
var Errors=ErrorCon;
if (Errors==1){
alert("Wrong password");
}
}
window.addEventListener?
window.addEventListener('load',init,false):
window.attachEvent('onload',init);
})();
The same structure works on a different page yet here it just doesnt do anything.
Help

undefined result javascript

I have a simple javascript code, that validate when you write a order number and generates tags with javascript(with bootstrap-tagsinput js):
var order = $('#order_number').val();
if ($.inArray(order, $('#input_order_tags').val()) >= 0) {
$('#input_order_tags').tagsinput('add', order);
return;
}
var params = {
email: email,
order_code: order
}
AjaxServices.validateOrderNumberByEmail(params, function(error, result) {
if (error)
alert(error);
else
$('#input_order_tags').tagsinput('add', result.order);
});
This works fine but, every time trigger the error message when send a order number:
Console chrome debug:
How I can avoid the error of alert?
This is not a javascript issue. Server-side in you application you use order_code in one of the calls which returns the error message you see in the ajax call. Debug the offending call server-side, see which call returns that error and adjust your code so it works properly.
There might be two possibilities
client side issue ( javascript error) if so, its because the field order_number is disabled field.
as mentioned in this link
undefined index on javascript dynamic variables when passing to php form
If so, remove that disabled and use read-only and check if it works, without any error.
Server side issue( ajax call) if so, server side code which performs on call of that ajax call is causing that issue.

How to find the URL of an external site's Javascript submit

I will do my best to try to explain this.
I am scraping a website for it's elements to then output in a different format. The problem that I am experiencing is the way that this site directs the user throughout the site is through a Javascript redirect.
When checking the 'a href' tag, this is the Javascript that shows up
javascript:doParamSubmit(2100, document.forms['studentFilteredListForm'], 'SSC000001MU9lI')
The SSC000001MU9lI changes for each element that it redirects to.
Is it possible to find a URL using this Javascript, so that I can reach the HTML page externally?
EDIT: Here is the doParamSubmit and doSubmit classes:
function doParamSubmit(event, form, parameter) {
form.userParam.value = parameter;
doSubmit(event, form);
}
function doSubmit(event, form)
{
// Make sure if something fails that the form can be resubmitted
try
{
// If this form has not been submitted yet... (except for IE)
if (allowSubmit == true && form != null && (submitted == false || isInternetExplorer6() || isInternetExplorer7()))
{
submitted = true;
form.userEvent.value = event;
// Fix for IE bug in which userEvent becomes a property array.
if (form.userEvent.length)
{
form.userEvent[0].value = event;
}
// Disable the form so the user can't accidentally resubmit the page
// (NOTE: this doesn't disable links (e.g. <a href="javascript:...">)
disableForm(form);
// If there is a populate form function, call it. If there are spell check fields on the
// page, populateForm is used to set hidden field values.
if (this.populateForm)
{
populateForm();
}
saveScrollCoordinates();
// resetSessionTimeout();
try
{
form.submit();
}
catch(e)
{
// Exceptions thrown here are only caused by canceling the submit in onbeforeunload, so ignore.
submitted = false;
}
}
if (allowSubmit == false)
{
alert(grabResource("message.pageLoading"));
}
}
catch(e)
{
submitted = false;
throw e;
}
}
I see 2 approaches.
You use a javascript enabled browser such as http://nrabinowitz.github.io/pjscrape/. I am not sure if you intend to just follow the links or instead grab the URL for some other use so your mileage may vary.
Find the doParamSumit() function in their page/scripts and analyze it to understand how it gets the URL - the one you have as an example looks like it grabs the action from a form perhaps? Once you know how the function work you might be able to harness that info in your scraping by using some regex to find URLs that match the doParamSubmit pattern and going from there. It's hard to say without seeing the function itself as well as the other links like it though.
Regardless of which method you choose I would begin by understanding the function - look for it in the code or loaded js files (you can also you things like javascript debuggers on most browsers to help you find it) and see what happens - it might be super obvious.
Also keep in mind that this might be a POST for a form - in which case the result of you following that link may not work if it expects valid form data.
Edit I see that you posted the function. It simply submits the form listed in the second parameter i.e. 'studentFilteredListForm'. While I don't think your scraping will go to far chasing forms you can still get the URL either with javascript if your scraper lets you (something like $('form[name=studentFilteredListForm]').attr('action') or using whatever language your are using for the scraper i.e. find the form and extract the action url (remembering that if there is no action it is probably posting back to the current URL)
But again... you might first manually get the URL of the form and see where that gets you. You might just get a page with form errors :)

Jquery validation before form submits to php

I have tried and tried with this and don't seem to be getting anywhere, so thought I would put it out there. I have a form full of data provided by the user that I have thus far been able to validate with js/jQuery without problem before sending it to php for further processing. I am achieving this like so:
form.submit(function(){
if(validateUserName() & validateEmail1() & validateEmail2() & validatePass1() & validatePass2() & acceptTerms()){
return true;
} else {
return false;
}
});
The form itself uses the following attributes:
<form id="signup" action="registration.php" method="post">
The problem function is acceptTerms(), which simply has to check that a checkbox is selected does not seem to work as it should (or as the rest of the validation functions do).
var termscons = $('input:checkbox[name=termscons]');
termscons.change(acceptTerms);
function acceptTerms(){
if($(termscons).is(':checked')) {
termsconsInfo.text("");
return true;
} else {
termsconsInfo.text("In order to join, you must accept these terms and conditions.");
return false;
}
}
I have integrated the termscons.change listener and termsconsInfo.text(""); to ensure that my selectors are pointing at the right thing, and that the function is being fired correctly (which it appears to, by changing the termsconsInfo.text when its state changes). When I try to submit the form however it appears to return false, since it does not submit. It should in fact be returning true, and posting my form over to my php script.
Am I going about this the right way? Is there something I have been missing when dealing with a checkbox as opposed to a textinput?
Please excuse my ignorance, this is all still very new to me.
First problem is that you are using & in your if statement. It needs to be &&.
Second problem is with acceptTerms (as you guessed):
var termscons = $('input:checkbox[name=termscons]');
termscons.change(acceptTerms);
function acceptTerms(){
if(termscons.is(':checked')) { // <-- termscons is already a jQuery object
termsconsInfo.text("");
return true;
} else {
termsconsInfo.text("In order to join, you must accept these terms and conditions.");
return false;
}
}
There might be more, but that is what I see for now.
i say forget reinventing the wheel and use something already tested for instance jQuery validate

using reCAPTCHA with ajax....javascript loading problem

I trying to implement reCAPTCHA in one of my forms,...but i am using ajax as the submission. (More specifically the prototype ajax.updater)
Once I submit and error check my form I try to load the reCAPCHTA widget thingy (in my updated div element) which basically just calls a javascript file like so:
<script type="text/javascript" src="http://api.recaptcha.net/challenge?k=6Le6SwUAAAAAAIWm8wCRFd8SrI-H0R1Yx4Tkw2Ks"></script>
However the JS file is not being read?...and i've tried all combination of evalScripts:true and evalJS:'force' etc. in the ajax.updater.....however i don't think I have a very good understanding of why the js file isn't processing :(
If anyone can shed some light on this issue I will be very appreciative.
Thanks, Andrew
This doesn't address your exact problem, but 'Dark Side of the Carton' has some excellent code for validating reCAPTCHA via jQuery AJAX which might help.
In summary:
Add the following Javascript:
$(function() {
function validateCaptcha() {
var challengeField = $('input#recaptcha_challenge_field').val(),
responseField = $('input#recaptcha_response_field').val();
// alert(challengeField);
// alert(responseField);
// return false;
var html = $.ajax({
type: 'POST',
url: 'ajax.recaptcha.php',
data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
async: false
}).responseText;
if (html.replace(/^\s+|\s+$/, '') == "success") {
$('#captchaStatus').html(' ');
// Uncomment the following line in your application
return true;
} else {
$('#captchaStatus').html(
'Your captcha is incorrect. Please try again'
);
Recaptcha.reload();
return false;
}
}
// Modified as per comments in site to handle event unobtrusively
$('#signup').submit(function() {
return validateCaptcha();
});
});
Then add the ajax.recaptcha.php file which: "outputs only the word “success” if the captcha matches and a message and the response from reCaptchta if it fails. This is important because we are looking for the word success in our validateCaptcha() function."
require_once('/inc/recaptchalib.php');
$publickey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // you got this from the signup page
$privatekey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$resp = recaptcha_check_answer(
$privatekey,
$_SERVER['REMOTE_ADDR'],
$_POST['recaptcha_challenge_field'],
$_POST['recaptcha_response_field']
);
if ($resp->is_valid) {
?>success< ?
} else {
die(
"The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")"
);
}
The example is in PHP, but I adapted it easily to work with Zope/Python
Be careful using any sort of client-side script, such as JavaScript, for validation. You have no control over the end-user's browser. The purpose of a CAPTCHA is to prevent automated submissions of a form. Anyone sophisticated enough to set that up isn't going to have a problem overriding your JavaScript validation and CAPTCHA checking. For example, they could set validateCaptcha() to always return true, bypassing your careful checks - or just disable JavaScript.
That being said, there's nothing wrong with performing the entire form submission with ajax and using the results of the CAPTCHA check to determine if the form gets processed or not.
The important point is that the decision of whether or not to handle the form has to be made on the server-side, not the client-side.
Why client-side validation is not enough
to answer my own question...
there is a reCAPTCHA AJAX api....which is pretty easy way to get around this problem:
link text
Also,..the documentation on the http://www.prototypejs.org/api/ajax/updater site.....talks about the evalscript option and how is only puts any javascript through the native eval() function....which kind of screws me over trying to implement error checking with WMD...but that's another story.
Andrew
If that's the literal code snippet you're using, you haven't closed the tag... so it wouldn't be evaluated.
call Recaptcha.reload(); on callback event in your Ajax code., it will reload new Recapcha every time that Ajax submitted
Hi Friend i found the answer
https://developers.google.com/recaptcha/docs/display?hl=es#AJAX
And in this how validate
http://blog.reaccionestudio.com/comprobar-recaptcha-con-ajax-usando-jquery/
Success for you
Securing AJAX calls with reCaptcha
function performAJAX() {
let captcha = $('[name=g-recaptcha-response]');
$.ajax({
url: 'ajaxHandler.html',
data: {
captcha: (captcha.length?captcha[0].value:''),
// other data fields
},
});
}
I have had similar issues with getting reCaptcha to play nicely when loaded into the page using jQuery's .load() method. Here is a page that has a novel solution: http://www.maweki.de/wp/2011/08/recaptcha-inside-a-with-jquery-ajax-or-load-dynamically-loaded-object/
Basically the reCaptcha API uses document.write method to display the reCaptcha. When you get jQuery invloved this won't work. Use this PHP code in place of loading recaptcha.js
<?php
$api = file_get_contents('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
$api = str_replace('document.write','$("body").append',$api);
echo $api;
?>
It just does a find for document.write and replaces it with $(selector).append.
Made my implementation work.

Categories

Resources