Strange GET Data Causing 404 Error - JavaScript Form Validation - javascript

I want to refer to this post, because it might relate:
Make Form Fields Optional with JavaScript Validation
I have a form with three optional fields, as described above. If I click the submit button, the JavaScript alerts come up, but the last one is a URL instead of the string I specify in the JavaScript function (the one that isn't an alert strong but an URL).
After a second, the page tries to go to an invalid URL:
localhost.../index.php/Don%27t%20forget%20the%20location.
As it turns out the Don%27t%20forget%20the%20location. is the alert string I have in the JavaScript function.
I thought that I might have some weird code that I accidentally pasted somewhere causing this but I scoured my files and found nothing out of the ordinary that would cause this. Not sure if this is a bug or something I'm doing wrong.
EDIT
I have JavaScript form validation functions like so:
function validate_name(field)
{
if (field == "") return "Please enter the name.\n";
return "";
}
function validate_specialty(field)
{
if (field == "") return "Please enter the specialty.\n";
return "";
}
function validate_location(field)
{
if (field == "") return "Don't forget the location.\n";
return "";
}
where the function that is called from the form's onSubmit is:
function validate_form(form)
{
name = validate_name(form.name.value);
specialty = validate_specialty(form.specialty.value);
location = validate_location(form.location.value);
if (name == "" || specialty == "" || location == "")
{
return true;
}
else
{
alert("You must enter at least one field:\n\n" + name + specialty + location);
return false;
}
}

It's because the variable location refers to window.location in that case (the url). So if you change your variable name, that should work:
userLocation = validate_location(form.location.value);
and
alert("You must enter at least one field:\n\n" + name + specialty + userLocation);

Related

jQuery - Checking val isn't empty and contains a specific piece of text

So I've got a .js file that checks that the values of my form. I'm trying to check that the form values aren't empty, and that one of the values contains a specific piece of text (in this case, my name). If the form does hold my name, then run the rest of the script.
Where I have commented //etc etc, an AJAX script is ran that posts to a PHP file.
This is all functioning as expected, until I run the additional if statement checking the input value for my name.
$('#submit').click(function(e){
this.enabled=true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === ""){
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if($('#name').val().indexOf("Rich") != -1){ // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
// etc etc
});
Question: How would I go about checking that the value of the id '#name' isn't empty, and that it contains a specific piece of text?
Thanks in advance,
Richie.
Solution:
I removed the additional if statement and included the following code.
var name = $('#name').val();
if ( name.indexOf("Rich") || $.trim($("#name").val()) === ""){
If you indent your code consistently, it's fairly clear why you have a problem:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
if ($('#name').val().indexOf("Rich") != -1) { // Note that this is WITHIN the `if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "")` condition
$('#message').html("You have entered the wrong name.");
return false;
}
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
If you want it to be handled, it needs to be an else if for that condition instead:
$('#submit').click(function(e) {
this.enabled = true;
if ($.trim($("#name").val()) === "" || $.trim($("#topic_title").val()) === "") {
$('#message').html('you did not fill out one of the fields').css("color", "#be4343")
return false;
} else if ($('#name').val().indexOf("Rich") != -1) { // without this if statement, the code runs fine.
$('#message').html("You have entered the wrong name.");
return false;
} else {
if ($('#name, #topic_title').length && $('#name, #topic_title').val().length) {
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}
}
// etc etc
});
(Well, as you have return, those could both just be if rather than else if...)
There are other problems though, for instance this expression in your final block:
$('#name, #topic_title').length
...which checks to see if either #name or #topic_title elements exist in your DOM at all (it doesn't do anything to check their values, and it doesn't require that they both exist, just one of them), and this:
$('#name, #topic_title').val().length
...will only check the value in #name, it will completely ignore the value in #topic_title, because when used as a getter, val only gets the value of the first element in the jQuery set. (Almost all of jQuery's functions that can be getters or setters are like that; the exception is text which is different from the others.)
Finally, this line:
this.enabled = true;
...is almost certainly a no-op, since the button cannot be clicked if it's not enabled, and as lshettyl points out, the property's name is disabled, not enabled. So this.disabled = false; if you're trying to enable it, or this.disabled = true; if you're trying to disable it.
By the look of your code, I assume you have a form that has either a class or an ID (or nothing). It'd be clever to use the form's submit event as opposed to click event of the submit button. This way you ensure that the form can also be submitted via the enter button (remember accessibility?). This is only an extension to T.J. Crowder's answer which has lots of good points from which you can learn/improve coding.
//Let's say your form has an ID 'topic'
$("#topic").on("submit", function() {
//Cache jQuery objects that would be resued, for better performance.
var $name = $("#name"),
$title = $("#topic_title"),
$msg = $('#message');
//One of the elements doesn't exist (exit)
//1 + 1 <= 1
if ($name.length + $title.length <= 1) {
return;
}
if ($.trim($name.val()) === "" || $.trim($title.val()) === "") {
$msg.html('you did not fill out one of the fields').css("color", "#be4343")
return;
} else if ($name.val().indexOf("Rich") !== -1) {
$msg.html("You have entered the wrong name.");
return;
} else {
//You do not need further checks such as length, val etc.
//as they have already been checked above.
var name = $name.val();
var topic_title = $title.val();
}
});
You can make comparison to know if it's empty:
if($('#name, #topic_title').length && $('#name, #topic_title').val().length){
var name = $("#name").val();
var topic_title = $("#topic_title").val();
}}
if(name=='' || name==undefined){
//do stuff here
}
});

Prevent form from being submitted and preserve data using Javascript onsubmit

So I have my form setup like this:
<form id="form" name='form' method="post" action="#" onsubmit="validate(this)">
and I have the following function to validate the form, but the problem is, when the validation fails, the form gets reset and thus you have to retype all the information. Although from what I've read having return false; in the validation function should prevent this, so what am I doing wrong?
var error = false;
var errors = [];
function validate(form)
{
var name = form.inputname.value;
var phone = form.inputphone.value;
var email = form.inputemail.value;
var make = form.inputmake.value;
var model = form.inputmodel.value;
var month = form.month.value;
var day = form.day.value;
if(!name || !phone || !email || !make || !model || !day || !month)
{
alert("Please complete the form");
errors[errors.length] = "Incomplete Form\n";
return false;
}
if (month < 1 || month > 12 || day < 1 || day > 30) {
alert("Please enter valid Month/Day in format 1-12/1-30 ");
document.getElementById("month").focus();
errors[errors.length] = "Invalid Date\n";
return false;
}
if (errors.length > 0) {
alert(errors);
return false;
}
else if (errors.length == 0)
{
window.location.href("reserved300771292.aspx");
}
return true;
}
Thanks in advance!!
Firstly although your function is correctly returning true or false depending on your requirement, you are not returning it to the onsubmit, so your form onsubmit should read
onsubmit="return validate(this)"
secondly you may experience an interesting bug due to the errors[] being global. If the first form validation fails, then every subsequent form submit will fail also (even if it is valid) as you are not clearing the errors array. Declare the errors[] variable inside the validate function.
Also I'm not sure the exact behavior you will get tring to redirect the browser in the validate function. This may stop the form from submitting (i.e. the data collected on the form will not be posted) or the redirect will not work. Personally I wouldn't try this approach, redirect on the server side if everything works the way it should, as it is best practice to validate server side and client side

What is a good strategy for custom form validation in angular?

As my app is growing, I'm finding more need for more effective form validation. I personally don't like the angular built in validation that evaluates on field change. And there are always things it won't account for like verifying that a youtube video id is valid. Currently I'm doing validation in each forms controller. I have a function that looks like this. Each field has a message and if there is an error the message will appear red using ng-class.
$scope.validate = function (callback) {
// reset default messages
setMessages();
// create shorter references
var item = $scope.item,
message = $scope.itemMessage;
// title exists
if (item.title === '') {
message.title.message = 'You must give your item a title.';
message.title.error = true;
message.errors += 1;
}
// extract and clear video id with youtube api
if ($scope.temp.video !== undefined && $scope.temp.video !== '') {
var id = '';
var url = $scope.temp.video.replace(/(>|<)/gi,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/);
if(url[2] !== undefined) {
id = url[2].split(/[^0-9a-z_]/i);
id = id[0];
} else {
id = url;
}
$http.get("http://gdata.youtube.com/feeds/api/videos/" + id)
.then(function (res) {
$scope.item.video = id;
}, function (res) {
message.video.message = 'That is not a valid youtube video.';
message.video.error = true;
message.errors += 1;
$scope.item.video = '';
});
}
if (message.errors === 0) {
callback();
}
};
and then my actual form submission function calls $scope.validate(); passing it a function containing the $http.post(). The two major problems I see are that my callback isn't promise base so there's no guarantee it won't be called when an error exists and I've read again and again to keep large chunks of logic outside of your controller. I haven't found great examples of how this should be done but it must be a common problem.
You can still use Angular's built-in validation and have it not evaluate unless the form has been submitted:
http://scotch.io/tutorials/javascript/angularjs-form-validation#only-showing-errors-after-submitting-the-form
Essentially you set $scope.submitted = true when the form is submitted and set a conditional check so that error messages and classes are only shown when $scope.submitted is set.

If, Or, while Not.... Javascript help needed

Hi folks I was curious if someone could help me out. I don't usually post on here but I have exhausted all my efforts and can't figure this out. I have this code here
function insertVideo(link)
{
if (link)
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
var editpane = document.frmPost.addesc;
var linkcode = "[EMBED]" + link + "[/EMBED]";
editpane.focus();
/*if (document.selection)
{
document.selection.createRange().text = linkcode;
}
else*/
if (editpane.selectionStart || editpane.selectionStart == '0')
{
var selstart = editpane.selectionStart;
var selend = editpane.selectionEnd;
editpane.value = editpane.value.substring(0, selstart) + linkcode + editpane.value.substring(selend);
editpane.selectionStart = selstart + linkcode.length;
editpane.selectionEnd = editpane.selectionStart;
}
else
{
editpane.value = editpane.value + linkcode;
}
editpane.focus();
}
}
The problem I am having is when the user trys top post a youtube video with https in the address.
I understand that if I change
{
if(link.substring(0,29)!="http://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
to
{
if(link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
It works. But then when the user enters the http address without the https it no longer works. I figured I could combine the statement with an OR, but this doesnt work either, I had
if(link.substring(0,29)!="http://www.youtube.com/watch?" || link.substring(0,30)!="https://www.youtube.com/watch?"){
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
else{
link = link.replace(/watch\?/,"").replace(/\=/,"/");
}
So basically I need it to work in both situations (https and http) not just one or the other.
I am stumped, Im no pro with javascript so I sure its a minor error but I have spent far too much time trying to figure this out on my own. Please help if you can. Thanks!
It's as simple as changing the OR (||) to an boolean AND (&&).
if (link.substring(0,29) !== "http://www.youtube.com/watch?" && link.substring(0,30) !== "https://www.youtube.com/watch?") {
alert("You did not enter a valid URL!\r\nPlease try again.");
return false;
}
// the else is unnecessary
// else {
link = link.replace(/watch\?/,"").replace(/\=/,"/");
// }
This works as in your original code, if your URL is http://, it will fail the https:// check (or vice versa), making the conditional true, therefore running your failure code. Changing it to && fixes it as the URL is now required to fail both tests to be invalid.
Just a little note: unless you're doing it deliberately (or in other special circumstances), you should use the === and !== forms of equality testing (instead of == and !=), as these fail automatically if they are of different types instead of converting the types implicitly.

Simple javascript form validation won't return true

I created this function where it checks for multiple textboxes if they have values onsubmit. Basically it is a javascript form validator. When there are empty textboxes, form shouldn't submit and alert the user that there are required fields. Now, this works for me perfectly, however, when there are values already and the form is submitted, it still doesn't submit even though it should. I created an if statement to check if the errorString is empty or null, if it is, the form should submit but what happens is that it alerts the user with a blank string. I think the code is still going inside the if(errorString!=null || errorString=="") statement even though it shouldn't.
Thanks in advance
Please see my code below:
function validateForm()
{
var txtTitle = document.forms["actionStepsForm"]["txtTitle"].value;
var txtRequestor = document.forms["actionStepsForm"]["txtRequestor"].value;
var txtReprocessingRequest = document.forms["actionStepsForm"]["txtReprocessingRequest"].value;
document.getElementById('rowCount').value = counter-1;
var errorString = "";
if (txtTitle==null || txtTitle=="")
{
errorString += "Title field is required. \n";
}
if (txtRequestor==null || txtRequestor=="")
{
errorString += "Requestor field is required. \n";
}
if (txtReprocessingRequest==null || txtReprocessingRequest=="")
{
errorString += "Reprocessing request FR is required. \n";
}
if (errorString!=null || errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
}
//implementation if HTML form
<form name="actionStepsForm" id="actionStepsForm" action="add_reprocessing.php?action=add" method="POST" onsubmit="return validateForm()">
errorString can never be null because you've initialized it with "" so you can remove the condition "errorString != null".
It should become
if (errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
I think the correct condition should be
if (errorString != null && errorString != "")
otherwise the engine evaluated the 'errorString != null' condition, which evaluates to true (since errorString is "" and not null), and enter the code block.
Change
if (errorString!=null || errorString!="")
to
if (errorString!=null && errorString!="")
You have two 'not' statements that cancel each other out (one must always be false). Change it to:
if (errorString!=null && errorString!="")
{
alert(errorString);
return false;
}
else
{
return true;
}
The wrong line is the one everyone pointed out:
if (errorString!=null || errorString!="")
But I would like to point that you don't need to check for errorString!=null because you already created the variable as an empty string in the beginning of your code:
var errorString = ""; //created errorString as empty string
Therefore it will never actually be null, because you never set it as null anywhere (that is, you never set it as errorString = null).
If there are no errors, it will be an empty string always. So this will suffice:
if (errorString!="") //if errorString is different than what we created at `var`
{
alert(errorString);
return false;
}
else
{
return true;
}
Try With Different Logic. You can use bellow code for check all four(4) condition for validation like not null, not blank, not undefined and not zero only use this code (!(!(variable))) in javascript and jquery.
function myFunction() {
var errorString; //The Values can be like as null,blank,undefined,zero you can test
if(!(!(errorString))) //this condition is important
{
alert("errorString"+errorString);
}
else
{
alert("errorStringis "+errorString);
}
}

Categories

Resources