Set HTML Input invalid on server - javascript

I'm using HTML5 form validation to validate my form. So if I validate it using Javascript, I can do something like that:
if (isInvalid())
{
myControl.setCustomValidity("my error message");
}
And it's working fine. My doubt is about server-side validation. The form is posted back to the same page, and if an error is detected, the input control should be considered invalid from the start, something like that:
<input type="text" name="id" invalid error-message="This id is already used" />
I don't want to use AJAX to make this validation, because I would have to 'hijack' and cancel the form submit, make the validation using AJAX, and then submit the form in javascript.

It is always better to iterate over context
You are not using AJAX and are sending form over http page load
One thing to keep in mind is either ways AJAX or otherwise form will only follow course on clicking of submit button. Hence the name form submission.
With in the form we have a field which may be valid or invalid.
If the field is invalid then run error which seems to work or if field is valid then simply glide through to next step in form submission.
On server side detect if field is invalid or not .... and do what ever is dependant on the context.
Issue on server side is it has nothing to do, nor controls and nor wants to control UI, html display in your browser.
All it handles is request i.e. GET, POST, PUT, HEAD etc and responds accordingly.
Browser sends page request to web server - it may pack form data or it may not pack form data dependant on the context.
Web server fetches the page and forwards if there is any packed form data with the request to the page and there is always lot more data getting passed around other then just form e.g. cookies, User agents, IPs etc
once the page is loaded into process stream you little bit of programming tells it to find form data if there is any and processes that for data to make a response out put.
So we are having a conflict of interest between point no 4 and point no 5.
Thing is your form is ultimately just a payload for HTTP (which is just a payload for tcp in turn and so on).
HTTP inherently does not and should not identify data types in payload, it is just an array for HTTP. KEYWORD FOCUS array.
You can select how to represent data in the array
It may look something like this
GET /?say=Hi&to=Mom HTTP/2.0
Host: foo.com
read more here how forms are sent to webserver
So bottom line forms are only going in some form of array format, we know arrays always have key value pair e.g. ['say' => 'hi'] there is key and there is value.
usually java-script does not offer out of the box key value pairing for arrays it has values and uses their index as key e.g. ['hi', 'there'] behind the scene is equivalent to in some hackyway to [0 => 'hi', 1 => 'there'] just keep that in mind java script does not offer multidimensional arrays out of the box.
so how does java script handle arrays or how we define it we it goes like this
var say = ['hi'];
now you may see whats happening around say=Hi in form data. There is massive array of Get with in which are key value pairs separated by &
for php sake it looks something like this
$_GET = [
'say' => 'hi',
'to' => 'mom']
we detect in page through $_GET['say'] which returns the value against it.
This is universal and will remain this for a long time to come.
What you are trying to do it attempting to detect on server from form data wither any of the key value pair has valid value or not.
Well reason why url sending is so fast it happens in less then 2 seconds gone from one part of the planet to another. While response as in downloading the web-page is so slow because inherently do not send html code through url request as show in example above. they send militaristic information understood universally.
This in turn means since there is html going to server then sever cannot detect any attributes they only have key value pair. So out attribute detection is out of window. Through error and trials we developers get the hang of this explicit revelation.
Anyways so how do we deal with this;
Some make cookies some make extra hidden fields
Then trigger on submit event on form to do the magic they need to do
some even run server side validation by running validation function on server e.g.
if($_GET['say' != 'hi'){do this thing something} else { do that thing}
Trust me there are always some kind of function or loop run on server side to make validation. WE have not found default validation way as of yet.
So we use form on submit event
document.getElementById('myform').onsubmit = function() {
var cheking = document.getElementById('myfield').value;
if(cheking != 'what ever you want'){
alert('fail!');
return false; // prevent the form to submit
}
}
This is the general idea dont submit form which is half crooked but incase it does need be sent then slight change of code
document.getElementById('myform').onsubmit = function() {
var cheking = document.getElementById('myfield');
if(cheking.value != 'what ever you want'){
cheking.value = 'invalid';
alert('fail!');
}
}
form will submit and on server side for that key we will have value as invalid so php side would be
if($_GET['myfield' = 'invalid'){stop processing or whatever else } else { keep on processing}
Because this had been going on for so and so and so long it became a standard of its own through input pattern attribute which takes care of all of the above on client side and is pretty much what you have done.
input pattren
bunch of regex to help you along
<!DOCTYPE html>
<html>
<body>
<h1>The input pattern attribute</h1>
<form action="">
<label for="country_code">Country code:</label>
<input type="text" id="country_code" name="country_code" pattern="[A-Za-z]{3}" required oninvalid="runvalidity(this)" oninput="this.setCustomValidity('')"
title="Three letter country code"><br><br>
<input type="submit">
</form>
<script>
function runvalidity(ele){
ele.setCustomValidity('Enter country name please');
ele.value = "invalid";
}
</script>
</body>
</html>
we created a pattern which on on submit event will manage and wont send form the in JavaScript we have run bunch of events on input field where we call custom function which makes UI as you wanted and alters the input value. if for any reason form does go through with invalid value we can then run server side validation as shown above using the same logic.
nevertheless browser will only send count_name=invalid or country_name=usa etc
Hope gist helps you understand whats behind the scene. my suggestion will be develop a UI context then fit in code logic (key word logic) matching both on client and server side.
I personally use pasterns and filet through same conditions on server side. some time client side logic can be tightened up so much there is lesser need to compare on server side. Again it depends how one fits in their code logic.

Related

How to transfer array values in JS to html before the file switches using Ajax

This is the HTML code in file 1, which is calling the function. It is linked to javascript
<form id='next' action='file2.html'>
<button id="nextTwo" onclick="nextTwo()">next2</button>
</form>
This is the JS code that receives the function.
function nextTwo(){
document.getElementById('question').innerHTML=question
}
It is searching for the id before the file changes to where the id is.
Every time I press the button that calls the function it gives me:
"TypeError: Cannot set properties of null (setting 'innerHTML')"
This is because it is searching for the id of "question" in file 1, but the id is in file 2. It tries to find the id in file 1, then it switches to file 2, where the id of "question" is.
How do I make it so that is switches to file 2 first, then searches for the id.
Maybe an if statement with a condition, if the file is switched, although I don't know the how to write that.
Thanks for your help.
This is my Js code, how do I place the arrays value into the file 2 using ajax?
let ants;
let question;
let squestion;
function check() //CHECK
{
switch(1){ //different header number is fine but do '' BUT input box will still be there
case 0:
ants = ['calculations']
question=["Element Symbol that has the atomic number of... ","atomic mass of (round to nearest whole number)..."]
squestion=["1. 50","2. 2","3. 20","4. K"]
case 1:
ants = ["0 (all atoms have a charge of 0)","11","11","4","9","Be","8","8","8"]
question=["Sodium has 11 protons and an mass of 23. What is the...","An atom has an atomic# of 4 and 5 neutrons What is the...", "Oxygen has 8 electrons and a mass of 16"]
squestion=["charge","atomic#","#of electrons", "#of protons","Mass","element symbol", "#of protons", "atomic#", "#of neutrons"]
// ants = ["Sn ","He ","Ca ","39 ", "32 ","Sn ","He ","Ca",]
// question=["Element Symbol that has the atomic number of... ","atomic mass of (round to nearest whole number)..."]
// squestion=["1. 50","2. 2","3. 20","4. K"]
break;
case 2:
ants = ["Carbon", "Chlorine", "Bromine",'Br',"Li","Sc","2","8","8" ]
question=["Carbon", "Chlorine", "Bromine", "Helium",'Br',"Li","Sc" ]
squestion=[]
}
There is a better way to go about this.
By design, forms do not communicate two-way. They take the data entered by the user and carry it over to the processing file (defined by the action= parameter on the form tag). The user is navigated away from the first webpage, and the view changes to that processing file - and it isn't supposed to go back to the first file again. Forms are very basic, primitive constructs.
This is why forms have been almost entirely replaced by AJAX. AJAX is a very simple JavaScript construct (made even simpler via jQuery - TANGENT: although jQuery is no longer recommended because modern JavaScript has made the process much easier - but the jQuery $.ajax() method still works fine and there is tons of info about how to use it).
AJAX allows you to send data from a web page to a back-end (server-side) file that receives any data you send it (optional), does something (optional), and returns new data (optional). The page the user is on need not change, blink or flash. New data received from the server-side file can be received and actively used before returning control to the user... So this sounds like exactly what you need it to do.
The back-end (AJAX) processing file is written in a server-side language (PHP, NodeJS, ASP.Net, Python, etc - PHP is a very popular one for AJAX), but you did not specify which one you wish to use, which is likely why no one responded to your question sooner.
Here are some references that might help. I chose jQuery examples because the AJAX code block $.ajax( //code goes here ).done() is very simple. To do AJAX in pure JavaScript, look for information regarding the Fetch API (newest), and XmlHTTPRequest (older).
Simple jQuery example
Ajax explained with jQuery
Another simple example with explanation
Here is a pure javascript video tutorial (5 mins)
After reviewing the examples, you can construct a basic AJAX test on your side and, if you have any trouble with it, ask another question specifying which language you are trying to do this with, and showing your code so far.

Best way to prevent parameter tampering and send values with Javascript?

I am posting a form to the controller and making it asynchronous. I am storing values in input form hidden. When a button is clicked, a javascript function is called. It both fetches the value from an input field, as well as a value from input form hidden. It then sends a json string to the controller to handle this request.
Controller:
[HttpPost, Authorize]
public ActionResult DoSomeStuff (string leagueName, string doSomething) {
var service = new Service(_db);
var league = service.GetLeague(leagueName);
if (league != null) {
// validate doSomething
league.Action = doSomething;
_db.SaveChanges();
}
return new EmptyResult();
}
Javascript:
$(document).on("click", "#submitForm", function () {
var json = {
"leagueName": $("input[name=leagueName]").val(),
"doSomething": $("input[name=doSomething]").val()
};
$.post("/Home/DoSomeStuff/", json, function () {
// async display something
});
}
Html:
<input type="text" name="doSomething">
<button type="submit" id="submitForm"</button>
<input type="hidden" name="leagueName" value="#item.League.LeagueName" />
What is the best way to let javascript fetch a stored value (more secure way then input type hidden)?
How can I prevent some user from altering the value from the input type
hidden field?
How can I prevent some user from altering the value from the input
type hidden field?
You cannot!
What is the best way to let javascript fetch a stored value (more
secure way then input type hidden)?
The general rule is, do not trust data coming from client. You should always validate it on server before doing anything.
If you are worried about a user update the league name field value in the form to some other users league name and post it, What you should be doing is, explicitly checking whether the user has proper permission to do something on the posted league in your server code.
[HttpPost, Authorize]
public ActionResult DoSomeStuff (string leagueName, string doSomething) {
var service = new Service(_db);
var league = service.GetLeague(leagueName);
// Now check whether the current user has access/permission
// to perform some operation on this league.
// Ex : if(!service.IsUserAuthorizedToDoSomething(league))
// {
// return View("NotAuthorized");
// }
//to do: Return something
}
If the value needs to come from the client (and be part of the HTTP request) then there's absolutely nothing you could do to prevent the client from modifying its contents. If the client is not supposed to modify the contents of some fields then those fields have nothing to do in your markup and be part of the postback HTTP requests (be it as hidden fields or whatever markup element comes to your mind). They should safely reside on your server (database?) and be retrieved using some identifier coming from the client. Obviously whether the client can access the information related to this identifier is subject to something called authorization. Basically you should first know who your client is (authentication) and then verify in your data model if this client has access to the corresponding records. It's as simple as that.
[HttpPost]
[Authorize]
public ActionResult DoSomeStuff (string id, string doSomething)
{
var service = new Service(_db);
var league = service.GetLeagueById(id);
if (!HasAccessToLeague(User.Identity.Name, league))
{
// you are not suppose to modify the contents of this league
// throw him a 404 or something
}
else
{
if (league != null)
{
// validate doSomething
league.Action = doSomething;
_db.SaveChanges();
}
}
return new EmptyResult();
}
obviously the implementation of the HasAccessToLeague(string username, string leagueId) method will greatly depend on your data model and how your authorization logic.
Also you used XSS in your question title but here your problem is not about XSS or javascript but rather designing authorization layer in your web application.
of course its possible to do this! After all, your server app manages to track who the currently logged on user is using insecure client storage.
When a user logs on, the server will generate a secret message and store it in an encrypted token that's passed to the client and bak in a cookie (which is just another piece of unsecured client data storage). When you send requests to the server, it gets the cookie, decrypts it, and checks the data inside to tell who the user is.
You can do the same - for the hidden fields, encrypt them, put them in a hidden input (or a cookie if you prefer) and send them back to the server. However, you can only use them in your client javascript if you send them plain text as well, which means you need to still perform some checking on the server, but that checking can be as simple as comparing the encrypted values with the hidden form values, if any do not match, reject the request.
things to bear in mind though, encrypion is slow. It can be quicker to fetch the values from a DB instead, though you might use a cache for these. YMMV.
An alternative option is to generate a javascript file with the values in and ensure that the client browser cannot edit them using security features such as content-security-policy. The disadvantage is an inability to use these values in html (as obviously the user can edit them there) so you'll have to pass data back to the server via js calls.

Fix cross site scripting issue

I have got a cross site scripting issue (reported by one of the tools)
I have a form on my screen with various fields.
Now if the user enters <script>alert("1")</script> tag for one of the field 1, browser is showing popup with value 1.
If user enters <html>testString</html> or <script>alert("1")</script> for field 1, it is being sent as encoded to server and retrieved back as encoded properly, but if the user does not modify field 1 containing these tags, but updates other fields like field 2, 3, field 1 is being messed up as it is being sent to server non encoded.
How can I fix this issue? Is there any standard way of fixing such issues ?
Also I use a Java resource where the form values are posted? So any changes to the same as well ?
For this you have to replace the characters like '<' to its corresponding html entity equivalent like '&lt'. Its better to done it on server side since client side validation can be blocked by user. In javascript we can do like this.
document.write(htmlentities("<script>"));
function htmlentities(str) {
var ret = str.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
return ret;
}

is it possible to share session variables between servlets/jsp and javascript functions?

I have a scenario where a form has to be filled in as easily as possible. The values to be filled in in the form, are asked from the user initially and stored in database.
Afterwards, when user clicks on a button, a javascript function is invoked that auto-fills all the fields in the form with values obtained by jsp/servlet.
I want to retrieve the values (that are to be filled in into the form) from database with the help of servlet/jsp...Now there should be some way for the javascript function to fill in this value (that was obtained by the servlet/jsp) into the form...
Is it possible to do such sharing of data/variables between jsp/servlets and javascript functions? The javascript functions will be part of the jsp (that retrieves the value that should be filled in in the form).
If the request is sent synchronously (e.g. a form submit button), then you don't necessarily need JS for this job. Just let JSP/EL print them immediately as input values based on data which is prepopulated by a servlet. For example, assuming that ${user} is a typical Javabean which is prepared by the servlet:
<input type="text" name="name" value="${fn:escapeXml(user.name)}" />
<input type="text" name="city" value="${fn:escapeXml(user.city)}" />
<input type="text" name="country" value="${fn:escapeXml(user.country)}" />
(the fn:escapeXml() is just to prevent XSS attacks)
If the request is sent asynchronously (e.g. using ajax), then you just need to let the servlet return the data in a format which is easily parseable by JS, for example JSON.
{
"username": "Bauke Scholtz",
"city": "Willemstad",
"country": "CuraƧao"
}
which you can then use as follows in the ajax response callback function (where user is the obtained JSON object):
document.getElementById("name").value = user.name;
document.getElementById("city").value = user.city;
document.getElementById("country").value = user.country;
jQuery makes things like this much easier. See also How to use Servlets and Ajax?
The Javascript client in the browser has no direct access to the environment on the server (and shoudln't - imagine how it would be bad if all pages broke the day you decided to use a diferent server solution). You basically have two choices:
Include all the data you will ever need on the page you serve to the client (perhaps the form html is dinamically generated to suit your needs, etc etc)
Manually request extra information dinamically via XMLHttpRequest (aka AJAX). This is the only way if you can only determine what data you will need dinamically, after the page loads.
You could access your database dynamiclly using xmlhttprequest.
For further information + relevant examples read :
http://www.w3schools.com/ajax/ajax_aspphp.asp

Reading and checking user's entry from a text field in an html form

What I want to do is to have a form field that allows a person to try to guess from a picture what type of bird it is, and if they get it right, it tells them they got it right and gives them the code to be able to get a discount.
Here is the code I'm using within the head tags:
formCheck()
{
var birdName = document.forms[0].birdName.value
if (birdName == "red bellied woodpecker")
alert("That's Correct! Please enjoy 10% off your next purchase by entering the code NAMETHATBIRD92 during checkout.")
else
alert("That's isn't the correct answer! Make sure your answer is very specific and keep trying, you can guess as many times as you want.")
}
Here is what I have within the body tag:
Can you name this bird?
It works here:
www.madhatwebsolutions.com/namethatbird.html
It does not work here, where I really need it to work:
http://www.wildbirdsmarketplace.com/pages/Name-That-Bird!.html
This shouldn't be JavaScript.
Any potential customer will be able to right click and view your JavaScript source and retrieve the code without bothering with the guesswork.
You'll need to query a server with the user input, and the server will need to return a response indicating whether this input is correct or not.
You might want to look at either a normal HTML form submission, or venture into AJAX
Workflow:
User enters guess into textfield
Launch a request to http://yourserver.com/check_bird.your_server_language?guess=theTextFieldValue
Server returns either a success or failure indication
Display response to client
Other things to consider: Are you going to allow your customers to guess multiple times, or restrict them? Are you going to be showing several different birds or not?
in http://www.wildbirdsmarketplace.com/pages/Name-That-Bird!.html
<script type="text/javascript" src="birdname.js"></script> refers to 404 - check the file path
don't use document.forms
var birdName = document.getElementById('birdName').value;

Categories

Resources