textbox accepts the following values in Javascript? - c#

I have a textbox and i need to validate that it accepts only 1,1.5,2,2.5,3,3.5,...11.5
How to validate it.. pls tell the answer please.
$(document).on('keyup', '#Dia_Inch', function (e) {
Dia_Inch = $(this).val();
if (Dia_Inch.charAt(1) == ".") {
if (Dia_Inch.charAt(2) != "5") {
this.value = '';
$('#Dia_Inch').val("");
alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
return false;
}
}
var val = isNumberInch(e);
if (val == false || Dia_Inch > 11.5) {
this.value = '';
$('#Dia_Inch').val("");
alert("Number must be between 0 and 11.5 If zero inches, must enter 0 Enter 1/2 inches as .5; -Ex. 3 and 1/2 inches entered as 3.5");
return false;
}
});
this my sample code.. but it wont be worked.

You can do this using jquery:
function validate(value){
var arr = [1,1.5,2,2.5,3,3.5,...11.5];
if($.inArray(value, arr) >= 0){
return true;
}
return false;
}
You'll have to modify this according to your needs.
Here is a fiddle: http://jsfiddle.net/5Cm2w/
Do not forget to update the array with your actual values.

This may solve your purpose.
$(function() {
$('button').on('click', function() {
var val = $.trim($('input[type="text"]').val());
if(val.length && $.isNumeric(val) && val.match(/^\d+(\.5{0,1})?$/)) {
alert('valid')
} else {
alert('invalid');
$.trim( $('input[type="text"]').val('') );
}
});
});
Demo
But if u want to allow up to 11.5 then
$(function() {
$('button').on('click', function() {
var val = $.trim($('input[type="text"]').val());
if(val.length && $.isNumeric(val) && val.match(/^[1-9]{1}[1]{0,1}(\.5{0,1})?$/)) {
alert('valid')
} else {
alert('invalid');
$.trim( $('input[type="text"]').val('') );
}
});
});
Demo

Related

Library for calculating GTIN from EAN-13 barcode

I am creating an XML from a backend that is supposed to be fed into a GDSN datapool. The company has a very old backend which only has their own PLU number and barcode attached to every item. What I know is that (at least here in Iceland) most GTIN are the EAN-13 barcode with a padded 0 at the front although this is not always the case. Do you know of a library that could check if a GTIN is correct i.e. would calculate the check digit?
I am using a windows form and am using C#.
First to validate what you want to do:
https://www.gs1.org/services/check-digit-calculator
Then you have 2 possibilities for GTIN since it must be 14 digits long.
The case you described, then you pad a 0 on the left
A GTIN with right length is provided directly (which is possible and left digit will not be 0)
Here is a quick example on how you can check this, based on the fact you know the gtin string only contains digits:
public Boolean ValidateGTIN(string gtin)
{
string tmpGTIN = gtin;
if (tmpGTIN.Length < 13)
{
Console.Write("GTIN code is invalid (should be at least 13 digits long)");
return false;
}
else if (tmpGTIN.Length == 13)
{
tmpGTIN = "0" + gtin;
}
// Now that you have a GTIN with 14 digits, you can check the checksum
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(tmpGTIN[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(tmpGTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
Thanks for that. This is almost there. I would like to take it a step further - I am going to copy your code and add a little:
//First create a function only for validating
//This is your code to almost all - variable names change
public Boolean validateGTIN(string gtin)
{
Boolean IsValid = false;
int Sum = 0;
int EvenSum = 0;
int CurrentDigit = 0;
for (int pos = 0; pos <= 12; ++pos)
{
Int32.TryParse(gtin[pos].ToString(), out CurrentDigit);
if (pos % 2 == 0)
{
EvenSum += CurrentDigit;
}
else
{
Sum += CurrentDigit;
}
}
Sum += 3 * EvenSum;
Int32.TryParse(GTIN[13].ToString(), out CurrentDigit);
IsValid = ((10 - (Sum % 10)) % 10) == CurrentDigit;
if (!IsValid)
{
Console.Write("GTIN code is invalid (wrong checksum)");
}
return IsValid;
}
//Here we change quite a bit to accommodate for edge cases:
//We return a string which is the GTIN fully formed or we throw and exception.
public String createGTIN(string bcFromBackend)
{
string barcodeStr = bcFromBackend;
//Here we check if the barcode supplied has fewer than 13 digits
if (barcodeStr.Length < 13)
{
throw new System.ArgumentException("Barcode not an EAN-13
barcode");
}
//If the barcode is of length 13 we start feeding the value with a padded 0
//into our validate fuction if it returns false then we pad with 1 and so on
//until we get to 9. It then throws an error if not valid
else if (barcodeStr.Length == 13)
{
if(validateGTIN("0"+ barcodeStr))
{
return "0" + barcodeStr;
}
else if(validateGTIN("1" + barcodeStr))
{
return "1" + barcodeStr;
}
else if(validateGTIN("2" + barcodeStr))
{
return "2" + barcodeStr;
}
else if(validateGTIN("3" + barcodeStr))
{
return "3" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("4" + barcodeStr))
{
return "4" + barcodeStr;
}
else if(validateGTIN("5" + barcodeStr))
{
return "5" + barcodeStr;
}
else if(validateGTIN("6" + barcodeStr))
{
return "6" + barcodeStr;
}
else if(validateGTIN("7" + barcodeStr))
{
return "7" + barcodeStr;
}
else if(validateGTIN("8" + barcodeStr))
{
return "8" + barcodeStr;
}
else if(validateGTIN("9" + barcodeStr))
{
return "9" + barcodeStr;
} else {
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode")
}
}
//Lastly if the barcode is of length 14 we try with this value. Else throw
//error
else if(barcodeStr.Length == 14)
{
if(validateGTIN(barcodeStr)
{
return barcodeStr;
}
else
{
throw new System.InvalidOperationException("Unable to create valid
GTIN from given barcode");
}
}
Hopefully this makes sense. I have not sent the code through testing as I don't have my IDE on my current computer installed. Is

MVC5 C# jQuery Unobtrusive Validation with ignore and Show/Hide Message

My users have requested that I change one of the fields from being required to optional, but still show/hide the warning message. Trying to do this with as little refactoring as I can I added an allowsubmission property on my data annotation on the server and in the jquery method on the client (see below).
Is it possible to set an ignore class on an element while still hiding/showing the message? It seems the method fires the first time and then stops firing after the ignore class is added, so the message stays on the screen.
Or is there a better way? Thank you.
$(document).ready(function () {
$("form").validate().settings.ignore = ".ignore, :hidden";
});
$.validator.unobtrusive.adapters.add('dependentrange', ['minvalueproperty', 'maxvalueproperty', 'allowsubmission'],
function (options) {
options.rules.dependentrange = options.params;
if (options.message) {
$.validator.messages.dependentrange = options.message;
}
}
);
$.validator.addMethod('dependentrange', function (value, element, params) {
var minValue = parseFloat($('input[name="' + params.minvalueproperty + '"]').val());
var maxValue = parseFloat($('input[name="' + params.maxvalueproperty + '"]').val());
var currentValue = parseFloat(value);
// if there is a value check it. If for some reason the min and max can't be found return true because
// i do not know the values to validate. Usually that is a coding mistake
if (isNaN(currentValue) || minValue > currentValue || currentValue > maxValue) {
var message = $(element).attr('data-val-dependentrange');
$.validator.messages.dependentrange = $.validator.format(message, minValue, maxValue);
if (params.allowsubmission) {
// once this property is added, the method does not fire
$(element).addClass("ignore");
}
return false;
}
$(element).removeClass('ignore');
return true;
}, '');
I ended up using validators API to show and hide my own warning message while always return true.
$.validator.unobtrusive.adapters.add('dependentrange', ['minvalueproperty', 'maxvalueproperty'], function (options) {
options.rules['dependentrange'] = options.params;
if (options.message) {
options.messages['dependentrange'] = options.message;
}
});
$.validator.addMethod("dependentrange", function (value, element, params) {
var valKeyed = parseFloat(value),
$elem = $(element),
$warning = $elem.closest('div').nextAll('.alert-warning:first')
msg = $elem.data('val-dependentrange),
isValid = this.optional(element) || valKeyed >= parseFloat(params.minvalueproperty) && valKeyed <= parseFloat(params.maxvalueproperty);
// there are no from or two found, so just return true with no warning
if (!params.minvalueproperty || !params.maxvalueproperty) {
return true;
}
if (isValid) {
$warning.text('')
$warning.addClass('hidden');
}
else {
$warning.text(msg)
$warning.removeClass('hidden');
}
return true;
});

AutoComplete triggered with two Special characters and two datasources

I have played with:
https://github.com/experteer/autocompleteTrigger/
as following:
(function ($, window, document, undefined) {
$.widget("ui.autocompleteTrigger", {
//Options to be used as defaults
options: {
triggerStart: "%{",
triggerEnd: "}"
},
_create: function () {
this.triggered = false;
this.triggered2 = false;
this.element.autocomplete($.extend({
search: function () {
/**
* #description only make a request and suggest items if acTrigger.triggered is true
*/
var acTrigger = $(this).data("autocompleteTrigger");
if (acTrigger.triggered == true || acTrigger.triggered2 == true) {
return true;
} else {
return false;
}
},
select: function (event, ui) {
/**
* #description if a item is selected, insert the value between triggerStart and triggerEnd
*/
var acTrigger = $(this).data("autocompleteTrigger");
var text = this.value;
var trigger = acTrigger.options.triggerStart;
var trigger2 = acTrigger.options.triggerStart2;
var cursorPosition = acTrigger.getCursorPosition();
var lastTrigger1Position = text.substring(0, cursorPosition).lastIndexOf(trigger);
var lastTrigger2Position = text.substring(0, cursorPosition).lastIndexOf(trigger2);
var lastTriggerPosition;
if (lastTrigger1Position > lastTrigger2Position) {
lastTriggerPosition = lastTrigger1Position;
} else {
lastTriggerPosition = lastTrigger2Position;
}
var firstTextPart = text.substring(0, lastTriggerPosition + trigger.length) + ui.item.value +
acTrigger.options.triggerEnd;
this.value = firstTextPart + text.substring(cursorPosition, text.length);
acTrigger.triggered = false;
acTrigger.triggered2 = false;
// set cursor position after the autocompleted text
this.selectionStart = firstTextPart.length;
this.selectionEnd = firstTextPart.length;
return false;
},
focus: function () {
/**
* #description prevent to replace the hole text, if a item is hovered
*/
return false;
},
minLength: 0
}, this.options))
.bind("keyup", function (event) {
/**
* #description Bind to keyup-events to detect text changes.
* If the trigger is found before the cursor, autocomplete will be called
*/
var acTrigger = $(this).data("autocompleteTrigger");
if (event.keyCode != $.ui.keyCode.UP && event.keyCode != $.ui.keyCode.DOWN) {
var text = this.value;
var textLength = text.length;
var cursorPosition = acTrigger.getCursorPosition();
var lastString;
var query;
var lastTriggerPosition;
var lastTriggerPosition2;
var trigger = acTrigger.options.triggerStart;
var trigger2 = acTrigger.options.triggerStart2;
if (acTrigger.triggered && text != "") {
// call autocomplete with the string after the trigger
// Example: triggerStart = #, string is '#foo' -> query string is 'foo'
$(this).autocomplete("option", "source", '/UITests/LookupFirst');
lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
query = text.substring(lastTriggerPosition + trigger.length, cursorPosition);
$(this).autocomplete("search", query);
}
if (acTrigger.triggered2 && text != "") {
// call autocomplete with the string after the trigger
// Example: triggerStart = #, string is '#foo' -> query string is 'foo'
$(this).autocomplete("option", "source", '/UITests/LookupSec');
lastTriggerPosition2 = text.substring(0, cursorPosition).lastIndexOf(trigger2);
query = text.substring(lastTriggerPosition2 + trigger2.length, cursorPosition);
$(this).autocomplete("search", query);
}
else if (textLength >= trigger.length) {
// set trigged to true, if the string before the cursor is triggerStart
lastString = text.substring(cursorPosition - trigger.length, cursorPosition);
acTrigger.triggered = (lastString === trigger);
acTrigger.triggered2 = (lastString === trigger2);
}
}
});
},
/**
* #description Destroy an instantiated plugin and clean up modifications the widget has made to the DOM
*/
destroy: function () {
// this.element.removeStuff();
// For UI 1.8, destroy must be invoked from the
// base widget
$.Widget.prototype.destroy.call(this);
// For UI 1.9, define _destroy instead and don't
// worry about
// calling the base widget
},
/**
* #description calculates the the current cursor position in the bound textfield, area,...
* #returns {int} the position of the cursor.
*/
getCursorPosition: function () {
var elem = this.element[0];
var position = 0;
// dom 3
if (elem.selectionStart >= 0) {
position = elem.selectionStart;
// IE
} else if (elem.ownerDocument.selection) {
var r = elem.ownerDocument.selection.createRange();
if (!r) return data;
var tr = elem.createTextRange(), ctr = tr.duplicate();
tr.moveToBookmark(r.getBookmark());
ctr.setEndPoint('EndToStart', tr);
position = ctr.text.length;
}
return position;
}
});
})(jQuery, window, document);
and in the View:
$('input,textarea').autocompleteTrigger({
triggerStart: '#',
triggerEnd: '',
triggerStart2: '##',
sourceOption1: '/UITests/LookupFirst',
sourceOption2: '/UITests/LookupSec'
});
Controller Action Method(LookupSec is identical) is:
public ActionResult LookupFirst(string q)
{
var list = new List<string>()
{
"Asp",
"BASIC",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
};
IEnumerable<string> data;
if (q != null)
{
data = list.Where(x => x.StartsWith(q));
}
else
data = list;
return Json(data, JsonRequestBehavior.AllowGet);
}
Now it supports two triggers # and # and two datasources for each one...
Problem is the searching doesnt work anymore, everything works as expected "Almost" but when i type something like "#as" it should filter the result but it doesnt!
any idea why this is not working ?
You seem to be using the LookupSec action to filter with the # character but in your question you have only shown the LookupFirst action which is associated with the # filter character. I have tested your code and it worked for # and not for # because LookupSec doesn't exist.
Once I have defined the LookupSec controller action it worked for both. Just be careful as right now you have hardcoded those action names in the widget itself so the sourceOption1 and sourceOption2 parameters will be completely ignored.
The query string parameter used by jquery autocomplete is called term, not q so fix your controller action as right now it isn't filtering anything:
public ActionResult LookupFirst(string term)
{
...
}

Multiple if conditions check in single button click

My C# code is something like as follows.
if(TextBox1.Text.Length > 5)
{
if(TextBox2.Text.Length > 5)
{
if(TextBox3.Text.Length > 5)
{
if(TextBox4.Text.Length > 5)
{
//Action to pass to the next stage.
}
else
{
error4.text = "Textbox4 value should be minimum of 5 characters.";
}
}
else
{
error3.text = "Textbox3 value should be minimum of 5 characters.";
}
}
else
{
error2.text = "Textbox2 value should be minimum of 5 characters.";
}
}
else
{
error1.text = "Textbox1 value should be minimum of 5 characters.";
}
1) In the above kind of sample. I am using nested If-Else concept where on button click, if TextBox1 value is less than 5 is moves to else part and shows the error1 value but it will not check for further errors.
2) If I change If conditions to step by step If conditions then it will not work for me because the action must be done only if all the IF conditions satisfies.
3) If I use && operator to check all conditions I will not get individual error to each "error label"
How can I check multiple IF conditions on a single button click?
My original code
if (checkavail == "available")
{
if (name.Text.Length > 0)
{
if (email.Text.Length > 5)
{
if (password1.Text.Length > 7 && password1.Text == password2.Text)
{
if (alternate.Text.Contains("#") && alternate.Text.Contains("."))
{
if (question.Text.Length > 0)
{
if (answer.Text.Length > 0)
{
Response.Redirect("next_page.aspx");
}
else
{
error5.Text = "Please enter your security answer";
}
}
else
{
error4.Text = "Please enter your security question";
}
}
else
{
error3.Text = "Invaild alternate email address";
}
}
else
{
error2.Text = "Password should be minimum 8 characters and must match confirm password";
}
}
else
{
error1.Text = "Email address should be minimum 6 characters";
}
}
else
{
error.Text = "Please enter your name";
}
}
else
{
error1.Text = "This email address is already taken. Please try another";
}
I need the Redirect action to be done upon satisfying all conditions. If more than one error was found each error should get each error message.
Make a function that just handles the error messages. Return an Enumerable from this function. Then you can format your if-statements like this and it will return an Enumerable:
private IEnumerable GetErrors()
{
if (TextBox1.Text.Length > 5) { yield return "Textbox1 minimum bla bla"; }
if (TextBox2.Text.Length > 5) { yield return "Textbox2 minimum bla bla"; }
if (TextBox3.Text.Length > 5) { yield return "Textbox3 minimum bla bla"; }
}
Make another function that handles your non-error message logic and just perform an if-statement to see if there were zero errors or not:
public void DoSomething()
{
var errors = GetErrors();
if (errors.Count == 0)
Response.Redirect("next_page.aspx");
else
error.Text = "Please fix your errors";
}
Thanks to all. I found my answer in below manner
string p1, p2, p3, p4;
if (TextBox1.Text.Length > 5)
{
p1 = "pass";
Label1.Text = "";
}
else
{
Label1.Text = "Textbox1 value should be minimum 5 characters.";
p1 = "fail";
}
if (TextBox2.Text.Length > 5)
{
p2 = "pass";
Label2.Text = "";
}
else
{
Label2.Text = "Textbox2 value should be minimum 5 characters.";
p2 = "fail";
}
if (TextBox3.Text.Length > 5)
{
p3 = "pass";
Label3.Text = "";
}
else
{
Label3.Text = "Textbox3 value should be minimum 5 characters.";
p3 = "fail";
}
if (TextBox4.Text.Length > 5)
{
p4 = "pass";
Label4.Text = "";
}
else
{
Label4.Text = "Textbox4 value should be minimum 5 characters.";
p4 = "fail";
}
if (p1 == "pass" && p2 == "pass" && p3 == "pass" && p4 == "pass")
{
Status.Text = "All pass";
}

Format Text from a Textbox as a Percent

I have a numeric value in a Textbox that I'd like to format as a percent. How can I do this in C# or VB.NET?
In VB.NET...
YourTextbox.Text = temp.ToString("0%")
And C#...
YourTextbox.Text = temp.ToString("0%");
Building on Larsenal's answer, how about using the TextBox.Validating event something like this:
yourTextBox_Validating(object sender, CancelEventArgs e)
{
double doubleValue;
if(Double.TryParse(yourTextBox.Text, out doubleValue))
{
yourTextBox.Text = doubleValue.ToString("0%");
}
else
{
e.Cancel = true;
// do some sort of error reporting
}
}
For added fun, let's make the parser a bit more sophisticated.
Instead of Double.TryParse, let's create Percent.TryParse which passes these tests:
100.0 == " 100.0 "
55.0 == " 55% "
100.0 == "1"
1.0 == " 1 % "
0.9 == " 0.9 % "
90 == " 0.9 "
50.0 == "50 "
1.001 == " 1.001"
I think those rules look fair if I was a user required to enter a percent. It allows you to enter decimal values along with percents (requiring the "%" end char or that the value entered is greater than 1).
public static class Percent {
static string LOCAL_PERCENT = "%";
static Regex PARSE_RE = new Regex(#"([\d\.,]+)\s*("+LOCAL_PERCENT+")?");
public static bool TryParse(string str, out double ret) {
var m = PARSE_RE.Match(str);
if (m.Success) {
double val;
if (!double.TryParse(m.Groups[1].Value, out val)) {
ret = 0.0;
return false;
}
bool perc = (m.Groups[2].Value == LOCAL_PERCENT);
perc = perc || (!perc && val > 1.0);
ret = perc ? val : val * 100.0;
return true;
}
else {
ret = 0.0;
return false;
}
}
public static double Parse(string str) {
double ret;
if (!TryParse(str, out ret)) {
throw new FormatException("Cannot parse: " + str);
}
return ret;
}
public static double ParsePercent(this string str) {
return Parse(str);
}
}
Of course, this is all overkill if you simply put the "%" sign outside of the TextBox.
A little trickery for populating Label's (& TexBox) in a panel before users input. This covers decimal, integers, percent, and strings.
Using C# 1.1 in the Page_Load event before any thing happens:
if (!this.IsPostBack)
{
pnlIntake.Visible = true // what our guest will see & then disappear
pnlResult.Visible = false // what will show up when the 'Submit' button fires
txtIperson.Text = "enter who";
lbl1R.Text = String.Format(Convert.ToString(0)); // how many times
lbl2R.Text = String.Format(Convert.ToString(365)); // days a year
lblPercentTime = String.Format("{0:p}", 0.00); // or one zero will work '0'
lblDecimal = String.Format("{0:d}", 0.00); // to use as multiplier
lblMoney = String.Format("{0:c}", 0.00); // I just like money
// < some code goes here - if you want
}

Categories

Resources