Multiline texbox validation - validation

I want to validate maxlegnth of 5 characters in each row of the multiline textbox
Help me

Here's an example: A TextArea and span to show the validation results.
<textarea cols="30" rows="10" onblur="validateRows(this)"></textarea><br/>
<span id="validationResults" style="color:red"></span>
Here's the JavaScript code to validate each row:
function validateRows(e){
var content = e.value.split("\n");
for(var line in content){
var charLength = content[line].length - 1;
var lineNumber = parseInt(line) + 1;
if(charLength > 5){
document.getElementById("validationResults").innerHTML += "* line "
+ lineNumber + " has " + charLength
+ " characters" + "<br/>";
}
}
}

This is a C# version. Can be used either in Web applications for server side validation or Windows applications. (In Web applications for client side validation, Jose Basilio's code is appropriate)
public static bool HasMax5CharsPerLine(TextBox target)
{
foreach (string Line in target.Text.Split(new char[] {'\n'}))
if (Line.Length > 5)
return false;
return true;
}

using split function(both in C# and Javascript) and then check length it.
var temp = [TextFromTextBox].split('\n');
foreach(var s in temp)
{
if(!ValidateFunction(s))
{
// code for show exception
}
}

Related

Edit UI bot framework

I read here that it was possible to display a message when the cursor is on a button of a promt. I looked a little on the net but I did not find what part of the botchat.js edit.
Can you teach me?
Thanks you
display a message when the cursor is on a button of a promt.
You could modify the botchat.js file to add title attribute to the button in order to shown it as a tooltip text when the mouse moves over the button, the following code snippet is for your reference.
Add add title attribute to actionButton element within ActionCollection.prototype.render function:
for (var i = 0; i < this.items.length; i++) {
if (isActionAllowed(this.items[i], forbiddenActionTypes)) {
var actionButton = new ActionButton(this.items[i]);
actionButton.element.style.overflow = "hidden";
actionButton.element.style.overflow = "table-cell";
actionButton.element.style.flex = this._owner.hostConfig.actions.actionAlignment === Enums.ActionAlignment.Stretch ? "0 1 100%" : "0 1 auto";
/*add title attribute to button*/
actionButton.element.title = this.items[i].title;
actionButton.text = this.items[i].title;
actionButton.onClick = function (ab) { _this.actionClicked(ab); };
this._actionButtons.push(actionButton);
buttonStrip.appendChild(actionButton.element);
this._renderedActionCount++;
if (this._renderedActionCount >= this._owner.hostConfig.actions.maxActions || i == this.items.length - 1) {
break;
}
else if (this._owner.hostConfig.actions.buttonSpacing > 0) {
var spacer = document.createElement("div");
if (orientation === Enums.Orientation.Horizontal) {
spacer.style.flex = "0 0 auto";
spacer.style.width = this._owner.hostConfig.actions.buttonSpacing + "px";
}
else {
spacer.style.height = this._owner.hostConfig.actions.buttonSpacing + "px";
}
Utils.appendChild(buttonStrip, spacer);
}
}
}
Test result:

Validation for textbox with two sets of phone numbers

I am trying to do a validation on a textbox that can allow the input of one or more phone number in a single textbox. What I am trying to do is to send an message to the phone numbers included in the textbox.
I have no problem when I enter just one set of number into the textbox and the message can be sent.
However, whenever I type two sets of digit into the same textbox, my validation error will appear.
I am using user controls and putting the user control in a listview.
Here are my codes:
private ObservableCollection<IFormControl> formFields;
internal ObservableCollection<IFormControl> FormFields
{
get
{
if (formFields == null)
{
formFields = new ObservableCollection<IFormControl>(new List<IFormControl>()
{
new TextFieldInputControlViewModel(){ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *" , IsMandatory = true, MatchingPattern = #"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},
});
}
return formFields;
}
}
And here is the codes for the button click event:
private void OkButton_Click(object sender, RoutedEventArgs e)
{
MessageDialog clickMessage;
UICommand YesBtn;
int result = 0;
//Fetch Phone number
var phoneno = FormFields.FirstOrDefault(x => x.Tag?.ToLower() == "phone").ContentToStore;
string s = phoneno;
string[] numbers = s.Split(';');
foreach (string number in numbers)
{
int parsedValue;
if (int.TryParse(number, out parsedValue) && number.Length.Equals(8))
{
result++;
}
else
{ }
}
if (result.Equals(numbers.Count()))
{
try
{
for (int i = 0; i < numbers.Count(); i++)
{
Class.SMS sms = new Class.SMS();
sms.sendSMS(numbers[i], #"Hi, this is a message from Nanyang Polytechnic School of IT. The meeting venue is located at Block L." + Environment.NewLine + "Click below to view the map " + Environment.NewLine + location);
clickMessage = new MessageDialog("The SMS has been sent to the recipient.");
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
YesBtn = new UICommand("Ok", delegate (IUICommand command)
{
timer.Stop();
idleTimer.Stop();
var rootFrame = (Window.Current.Content as Frame);
rootFrame.Navigate(typeof(HomePage));
rootFrame.BackStack.Clear();
});
clickMessage.Commands.Add(YesBtn);
clickMessage.ShowAsync();
}
}
catch (Exception ex)
{ }
}
}
I am trying to separate the two numbers with ";" sign.... and I am wondering if that is the problem. Or maybe it is the matchingpattern that I have placed in.
The answer is quite simple, create a bool property in your TextFieldInputControlViewModel something like
public bool AcceptMultiple {get;set;}
and to keep things dynamic, create a char property as a separator like below:
public char Separator {get;set;}
Now, modify your new TextFieldInputControlViewModel() code statement by adding values to your new fields like below:
new TextFieldInputControlViewModel(){Separator = ';', AcceptMultiple = true, ColumnWidth = new GridLength(350) ,HeaderName = "Recipient's mobile number *" , IsMandatory = true, MatchingPattern = #"^[\+]?[1-9]{1,3}\s?[0-9]{6,11}$", Tag="phone", ContentHeight = 45, ErrorMessage = "Please enter recipient mobile number. "},
Once it's done, now in your checkValidation() function (or where you check the validation or pattern match) can be replaced with something like below:
if(AcceptMultiple)
{
if(Separator == null)
throw new ArgumentNullException("You have to provide a separator to accept multiple entries.");
string[] textItems = textField.Split(Separator);
if(textItems?.Length < 1)
{
ErrorMessage = "Please enter recipient mobile number." //assuming that this is your field for what message has to be shown.
IsError = true; //assuming this is your bool field that shows all the errors
return;
}
//do a quick check if the pattern matching is mandatory. if it's not, just return.
if(!IsMandatory)
return;
//your Matching Regex Pattern
Regex rgx = new Regex(MatchingPattern);
//loop through every item in the array to find the first entry that's invalid
foreach(var item in textItems)
{
//only check for an invalid input as the valid one's won't trigger any thing.
if(!rgx.IsMatch(item))
{
ErrorMessage = $"{item} is an invalid input";
IsError = true;
break; //this statement will prevent the loop from continuing.
}
}
}
And that'll do it.
I've taken a few variable names as an assumption as the information was missing in the question. I've mentioned it in the comments about them. Make sure you replace them.

Import from CSV into HandsOnTable and Export to CSV from HandsOnTable

I am using http://handsontable.com/ as one of the widgets for showing prices for my project, I could not find export and import from CSV feature in their API or FAQ.
Has anyone implemented or know about it ?
Yup, that comment links you to the explanation on how to do it, and here is my implementation of it for anyone that wants to just reuse code. There are a few enhancements beyond the basic CSV exporting like the escaping of spaces and special characters, as well as apostrophes. It also sets the column headers if they exist so remove that line if you don't have column headers.
The relevant code assuming you have a button with id=export-csv:
function parseRow(infoArray, index, csvContent) {
var sizeData = _.size(hot1.getData());
if (index < sizeData - 1) {
dataString = "";
_.each(infoArray, function(col, i) {
dataString += _.contains(col, ",") ? "\"" + col + "\"" : col;
dataString += i < _.size(infoArray) - 1 ? "," : "";
})
csvContent += index < sizeData - 2 ? dataString + "\n" : dataString;
}
return csvContent;
}
/**
* Export to CSV button
*/
var exportCsv = $("#export-csv")[0];
if (exportCsv) {
Handsontable.Dom.addEvent(exportCsv, "mouseup", function(e) {
exportCsv.blur(); // jquery ui hackfix
var csvContent = "data:text/csv;charset=utf-8,";
csvContent = parseRow(colHeaders, 0, csvContent); // comment this out to remove column headers
_.each(hot1.getData(), function(infoArray, index) {
csvContent = parseRow(infoArray, index, csvContent);
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", $("h1").text() + ".csv");
link.click();
})
}
Hope it helps!

Get variable from web page with javascript in C++ Builder

I have a MiFi modem (Huawei e5776) which comes with its own web page that displays total traffic per month. I want to extract this value and display a meter in the icon tray. I'm sure this is possible in C++ Builder (or Delphi) but even though I'm pretty experienced in using C++ Builder, I am not in anything web related. Can someone give me some pointers how to do this? I assume I need to run the script and then extract the variable somewhere, how do I do this?
Thanks.
PS: I'd add the contents of the page but can't see a way to attach a document. Here's the first few lines..
// JavaScript Document
var g_monitoring_traffic_statistics = null;
var g_wlan_security_settings = null;
var g_wlan_basic_settings = null;
var g_connection_trafficresponse = null;
//Prefix string of ssid2 of Multi-SSID
var g_prefixWifiSsid = "ssid2_";
function getTrafficInfo(bit) {
var final_number = 0;
var final_str = "";
if(g_monitoring_dumeter_kb > bit) {
final_number = formatFloat(parseFloat(bit), 2);
final_str = final_number + " B";
}
else if(g_monitoring_dumeter_kb <= bit && g_monitoring_dumeter_mb > bit) {
final_number = formatFloat(parseFloat(bit) / g_monitoring_dumeter_kb, 2);
final_str = final_number + " KB";
}
else if(g_monitoring_dumeter_mb <= bit && g_monitoring_dumeter_gb > bit) {
final_number = formatFloat((parseFloat(bit) / g_monitoring_dumeter_mb), 2);
final_str = final_number + " MB";
}
else if(g_monitoring_dumeter_gb <= bit && g_monitoring_dumeter_tb > bit) {
final_number = formatFloat((parseFloat(bit) / g_monitoring_dumeter_gb), 2);
final_str = final_number + " GB";
}
else {
final_number = formatFloat((parseFloat(bit) / g_monitoring_dumeter_tb), 2);
final_str = final_number + " TB";
}
return final_str;
}
I suggest you to use a great html wrapper (named BCB HTML) for mshtml writed specially for C++Builder; With this wrapper you can execute java script inside C++ Builder cpp codes:
THTMLDocument document;
document.create();
document.write(
"<html><body><script>"
"function myFunc(n)"
"{"
"return n * n;"
"}"
"</script></body></html>");
document.parentWindow.execScript("alert(myFunc(3))", "javascript");
For your jscript:
String value = document.parentWindow.execScript("getTrafficInfo(1024)", "javascript");
Also it is possible to handle html events inside BCB, access html objects , ...
you can download it from here.
To use this source add html.cpp to your project.
If you use TWebBrowser to load a html page, you need just define document in global scope and write below code to connect/attach document variable to WebBrowser1->Document:
void __fastcall TForm1::WebBrowser1DocumentComplete(TObject *ASender,
const IDispatch *pDisp, const OleVariant &URL)
{
document.documentFromVariant(WebBrowser1->Document);
String value = document.parentWindow.execScript("getTrafficInfo(1024)", "javascript");
}

Applying rules in Telerik MVC Grid Filter

I'm using Telerik MVC Grid, and need to apply filter rules below, but it seems only apply to the first two column, and ignore all the rest of the columns.
Here JS Code : ( assume grid is $("#grid").data("tgrid") )
function extTelerikGridFilter(grid, value) {
if (!$.isArray(grid.columns)) throw "Error : First Parameter accept only array.";
var colLength = grid.columns.length - 1;
var filterText = "";
var tempArr = new Array();
for (var i = 0; i < grid.columns.length; i++) {
filterText = filterText + "substringof({0},'{1}')".replace("{0}", grid.columns[i].member).replace("{1}", value);
if (colLength > 0) {
filterText = filterText + "~or~";
colLength = colLength - 1;
}
}
console.log(filterText);
grid.filter(filterText);
}
Result of console.log(filterText) :
substringof(Doc_No,'Opriyandi')~or~substringof(Type,'Opriyandi')~or~substringof(Request_By,'Opriyandi')~or~substringof(Request_Date,'Opriyandi')~or~substringof(Department,'Opriyandi')~or~substringof(Plant,'Opriyandi')~or~substringof(Description,'Opriyandi')~or~substringof(IT_Support,'Opriyandi')~or~substringof(Status,'Opriyandi')
Look before and after applying the filters in attachment.
Is this some kind of bug or perhaps i did something wrong.. Thank You.
*Using Telerik MVC 2011.3.1229
*Please ask me if you need additional information regarding my issue. :)
Attachment :
- BeforeApplyingFilter.png
- AfterApplyingFilter
I had this problem too. After some experiments, I found that we should bracket every expression starting from the head.
So, your filter string would look like this:
(((((((((substringof(Doc_No,'Opriyandi'))~or~substringof(Type,'Opriyandi'))~or~substringof(Request_By,'Opriyandi'))~or~substringof(Request_Date,'Opriyandi'))~or~substringof(Department,'Opriyandi'))~or~substringof(Plant,'Opriyandi'))~or~substringof(Description,'Opriyandi'))~or~substringof(IT_Support,'Opriyandi'))~or~substringof(Status,'Opriyandi'))
You can modify your code:
..
for (var i = 0; i < grid.columns.length; i++) {
--> filterText = "(" + filterText + "substringof({0},'{1}')".replace("{0}", grid.columns[i].member).replace("{1}", value) + ")"; <--
if (colLength > 0) {
filterText = filterText + "~or~";
colLength = colLength - 1;
}
..
PS I'm using 2011.3.1306
PS2 I wrote the article about custom filtering - please see link.

Resources