I'm trying to pass some values from a textbox to an http adapter and it have the following error:
Here is the index.html
Username:<br>
<input type="text" name="username" id="username"><br>
Password:<br>
<input type="text" name="password" id="password"><br>
<button onclick="mobgetVerify()">Login</button>
<p>
<p id="demo"></p> <br />
<br />
<br />
mains.js
function mobgetVerify() {
alert("Hi" + $('#username').val() + $('#password').val());
var invocationData = {
adapter : 'LoginAdapter',
procedure : 'getVerify',
parameters : [ $('#username').val() , $('#password').val() ]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : getVerifySuccess,
onFailure : getVerifyFailure,
});
};
function getVerifySuccess(res) {
var httpStatusCode = res.status;
if (200 == httpStatusCode) {
var invocationResult = res.invocationResult;
var isSuccessful = invocationResult.isSuccessful;
if (true == isSuccessful) {
$("#demo").html(JSON.stringify(res.responseJSON.data));
if (res.responseJSON.data== "True "){
window.location="pages/view.html";
}
alert("Success: Value= " + res.responseJSON.data);
} else {
alert("Error. isSuccessful=" + isSuccessful);
}
} else {
alert("Error. httpStatusCode=" + httpStatusCode);
}
};
function getVerifyFailure(result){
alert("Verification Failure");
};
I would highly appreciate if i can get some help. Thank you.
The provided sample application worked just fine... I received an alert dialog with the text: "Success: Value=False".
The only difference I can think of, which relates every time in each of your questions... if the IP address. In your provided LogCat, it shows the server's IP address is "10.0.0.3", whereas mine is my actual IP address (9.148.x.y in my case).
As you were previously advised - use the correct IP address of the server in wlclient.properties.
To check for mine, I typed the following in Terminal: ifconfig (in Windows - "ipconfig").
Related
I want to create a simple form where user enters some string (key that authorizes them to upload a file) and the file they want to upload (no size limit, can be even 10GB or more).
The problem I have is that I don't know how to verify the code BEFORE accepting the file.
So far I have this code that disallows any upload even with a valid code since the uploaded file seems to be always the first form element to be checked.
(when I reversed the order of elements in the form this code didn't handle the request at all)
var isAuth = false
multipart.forEachPart { part ->
when (part) {
is PartData.FormItem -> {
val name = part.name
if(name != null && name == "key")
isAuth = isKeyValid(part.value)
}
is PartData.FileItem -> {
if(!isAuth) {
call.respond("Request not authorized")
call.response.status(HttpStatusCode.Forbidden)
part.dispose
return#forEachPart
}
if(part.originalFileName.isNullOrEmpty() || part.originalFileName!!.isBlank()) {
call.respond("Illegal filename")
call.response.status(HttpStatusCode.BadRequest)
return#forEachPart
}
val targetDir = File(uploadDir.path + File.separator + randomId)
targetDir.mkdir()
val targetFile = File(targetDir.path + File.separator + part.originalFileName)
targetFile.createNewFile()
sb.append(randomId)
sb.append("/")
sb.append(part.originalFileName)
sb.append("\n")
part.streamProvider().use { input -> targetFile.outputStream().buffered().use { output -> input.copyToSuspend(output) } }
}
}
part.dispose
}
HTML form I'm using:
<html>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="text" name="key">
<input type="submit" value="upload" name="submit">
</form>
</body>
</html>
Add Authentication feature
implementation "io.ktor:ktor-auth:$ktor_version"
Install the feature
install(Authentication) { //set type of authenction here }
Wrap your call in authenticate {} block
authenticate("auth") {
post(FORM) {
}
}
More Info: Ktor Authentication
I have an issue in validating multiple comma separated email address to one recipient field. I have no issue in validating one email. Any pointers are much appreciated. My code is below thanks.
html
<form ng-submit="onSend()" [formGroup]="sendEmailForm">
<div class="email-field">
<mat-form-field>
<input matInput #emailTo placeholder="to#company.ca, to#company.ca..." formControlName="toAddress">
</mat-form-field>
</form>
Typescript
ngOnInit() {
this.sendEmailForm = this.fb.group({
toAddress: new FormControl('', [Validators.email, Validators.required])
});
}
Will I have to write any custom validator?
You could create custom validator which calls Validators.email for each email in input value - stackblitz
commaSepEmail = (control: AbstractControl): { [key: string]: any } | null => {
const emails = control.value.split(',').map(e=>e.trim());
const forbidden = emails.some(email => Validators.email(new FormControl(email)));
return forbidden ? { 'toAddress': { value: control.value } } : null;
};
and use it like
this.sendEmailForm = this.fb.group({
'toAddress': ['', [Validators.required, this.commaSepEmail]]
});
I have a super simple code I'm trying to validate:
<template>
<form role="form" submit.delegate="submit()" validate.bind="validation">
<div class="form-group">
<label>Test Field</label>
<input type="text" value.bind="testField" class="form-control" validate="Description" placeholder="What needs to be done?" />
<button type="submit">Submit</button>
</div>
</form>
</template>
With the following viewmodel
define(["require", "exports", "../scripts/HttpClient", "aurelia-validation", "aurelia-framework"], function(require, exports, HttpClient) {
var AureliaValidation = require('aurelia-validation').Validation;
var MyViewModel = (function () {
function MyViewModel(httpClient, aureliaValidation, isReadyCallback) {
this.httpClient = httpClient;
var self = this;
self.setupValidation(aureliaValidation);
}
MyViewModel.prototype.activate = function (params, queryString, routeConfig) {
};
MyViewModel.prototype.setupValidation = function (validation) {
this.testField = "";
this.validation = validation.on(this).ensure('testField');
//validation
// .on(this.serviceMetadata.ServiceData[0])
// .ensure('Value');
this.validation = this.validation.notEmpty().maxLength(3);
};
MyViewModel.prototype.submit = function () {
debugger;
if (this.validation.checkAll()) {
//Do Something
}
return null;
};
MyViewModel.inject = [HttpClient, AureliaValidation];
return MyViewModel;
})();
return MyViewModel;
});
Now I got it working for the most part, and the validation is showing false on submit check, the textbox outline color changes etc., however it's not injecting the validation error messages into the DOM. There's no script error message either, how can I troubleshoot this?
Yes, I can see the validation messages in the validationProperties, but they're not written to the UI.
If your browser allows it, find the JSPM packages in the sources and put a breakpoint here, it's the point where the view strategy looks for labels to append error messages to. If you'd have this code in the open, I'd be happy to have a look for you.
Also, what version of aurelia/aurelia-validation are you using?
And finally, did you modify your sample before posting?
`<input value.bind="testField" validate="Description" />`
These two attributes are contradictory. It binds the value to testField, but then you use the validate attribute to explicitly show validation messages for property "Description".
I'm using knockout validation and the error class is being added to the EndDate field but not the StartDate field when it't empty. the class caused the field to have a red background. I can't see any difference in the two fields. Something similar is happening on my other pages also.
Upon further investigation i realize it's always the first date field on the page that doesn't work. If I comment out the first one then the second stops working.
**Edit: as a hack I added this above the first date field
<input id="StartDate2" style="width: 140px;" type="hidden" data-bind="date: startDate">
and it works......but just feels really wrong.**
I have this at the beginning of my view model
ko.validation.init({
insertMessages: false,
decorateElement: true,
errorElementClass: "input-validation-error"
});
from my model
startDate: KnockoutObservable<Date> = ko.observable(null).extend({ required: { message: "Please enter a start date." }, simpleDate: { message: "Please enter a valid start date." } });
endDate: KnockoutObservable<Date> = ko.observable(null).extend({ required: { message: "Please enter an end date." }, simpleDate: { message: "Please enter a valid end date." } });
from the view
<li>
<label for="StartDate" class="required_label">Start Date</label>
<input id="StartDate" style="width: 140px;" type="text" data-bind="date: startDate, valueUpdate: 'afterkeydown', class:{'input-validation-error':(!startDate.isValid() && showErrors())}" ">
</li>
<li>
<label for="EndDate" class="required_label">End Date</label>
<input id="EndDate" style="width: 140px;" type="text" data-bind="date: endDate">
</li>
And here's our custome date binding handler
// mm/dd/yyyy format
ko.bindingHandlers.date = {
init: (element, valueAccessor) => {
$(element).mask("99/99/9999", { placeholder: "mm/dd/yyyy" });
ko.utils.registerEventHandler(element, "change", () => {
var value = valueAccessor();
if (moment(element.value).isValid()) {
value(element.value);
} else {
value(null);
}
});
ko.validation.makeBindingHandlerValidatable("date");
},
update: (element, valueAccessor, allBindingsAccessor) => {
var value = valueAccessor();
var allBindings = allBindingsAccessor();
var valueUnwrapped: any = ko.utils.unwrapObservable(value);
var pattern = allBindings.format || "MM/DD/YYYY";
var output = null;
if (valueUnwrapped !== null && valueUnwrapped !== undefined && valueUnwrapped.length > 0) {
output = moment(valueUnwrapped).format(pattern);
}
if ($(element).is("input") === true) {
$(element).val(output);
} else {
$(element).text(output);
}
}
};
You are making your date custom binding "validation compatible" only in its init function which will be only called when the binding is first used in the HTML. That is why the validation was only worked for the second input.
In order to fix this you have to move the ko.validation.makeBindingHandlerValidatable("date"); outside of your init function and have it after the whole binding handler declaration
ko.bindingHandlers.date = {
//...
};
ko.validation.makeBindingHandlerValidatable("date");
Hey I am using IBM Worklight V6.2.I want to insert values into database
My Html Code is
<h1>Please Enter The Car Details</h1>
<form >
Car No:<input type="number" id="carnum" placeholder="Please enter your no" ><br><br>
Details:<input type="text" id= "details" placeholder="Please enter car details" > <br><br>
<input type="submit" value="Register" onclick="loadFeeds1()">
</form>
My procedure is:
var users = WL.Server.createSQLStatement("insert into car(carno,details) values (?,?)");
function getusers(carno,details) {
return WL.Server.invokeSQLStatement({
preparedStatement : users,
parameters : [carno,details]
});
}
My js file is this
function loadFeeds1(){
var invocationData = {
adapter:"car2",
procedure:"getuser",
parameters:["carno","details"]
};
WL.Server.invokeProcedure(invocationData,{
onSuccess :loadFeedsSuccess1,
onFailure :loadFeedsFailure1,
});
}
function loadFeedsSuccess1() {
WL.Logger.debug("inserted");
}
function loadFeedsFailure1() {
WL.Logger.debug("failed");
}
I am able to invoke procedure from adapter..but not able to see when i insert values in browser.not it is showing anything in console..Kindly suggest...
You can't simply place the IDs of your inputs as the WL.client.invokeProcedure's parameters... You need to pass their value.
For example:
function loadFeeds1(){
var invocationData = {
adapter:"car2",
procedure:"getuser",
parameters:[$('#carnum').val(),$('#details').val()]
};
WL.Server.invokeProcedure(invocationData,{
onSuccess :loadFeedsSuccess1,
onFailure :loadFeedsFailure1,
});
}
This is an end-to-end scenario, where I take 2 values from the HTML and insert them into the database. To re-create, you can you use the WorklightTraining.sql scheme provided in the Adapters sample project. You can see it works because after the 'success', if you will refresh the database - you'll see the new record.
HTML:
<h1>Test Insert Into Database</h1>
<input type="text" id="value1" placeholder="value1"/><br/>
<input type="text" id="value2" placeholder="value2"/><br/>
<input type="button" value="Insert values to database" onclick="insertValuesToDB();"/>
main.js:
function insertValuesToDB() {
var invocationData = {
adapter: 'insertValuesAdapter',
procedure: 'insertValuesProcedure',
parameters: [$('#value1').val(), $('#value2').val()]
};
WL.Client.invokeProcedure(invocationData, {onSuccess: insertSuccess, onFailure: insertFailure});
}
function insertSuccess() {
alert("success");
}
function insertFailure() {
alert("failure");
}
Adapter XML:
...
...
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<dataSourceDefinition>
<driverClass>com.mysql.jdbc.Driver</driverClass>
<url>jdbc:mysql://localhost:3306/worklight_training</url>
<user>Worklight</user>
<password>Worklight</password>
</dataSourceDefinition>
</connectionPolicy>
<loadConstraints maxConcurrentConnectionsPerNode="5" />
</connectivity>
<procedure name="insertValuesProcedure"/>
...
...
Adapter implementation:
var insertValuesProcedureStatement = WL.Server.createSQLStatement("INSERT INTO users(userId, firstName, lastName, password) VALUES (?,?, 'someLastName', 'somePassword')");
function insertValuesProcedure(value1,value2) {
return WL.Server.invokeSQLStatement({
preparedStatement : insertValuesProcedureStatement,
parameters : [value1,value2]
});
}