TextBox validation Issue - javascript

i have a textbox and its javascript function declared as follows
<asp:TextBox ID="TextBox1" runat="server" onKeyUp="javascript:Count(this);" TextMode="Number"></asp:TextBox>
function Count(text) {
//asp.net textarea maxlength doesnt work; do it by hand
var maxlength = 4; //set your value here (or add a parm and pass it in)
var object = document.getElementById(text.id) //get your object
if (object.value.length > maxlength) {
object.focus(); //set focus to prevent jumping
object.value = text.value.substring(0, maxlength); //truncate the value
object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
return false;
}
return true;
}
I have also set the TextMode property of TextBox to Number, but i can still enter the Alphabet "e/E" and while entering this particular alphabet my javascript function is also not called. How should i solve this problem.

Try this. You can use multiple data types for validating the input. And you can just use the MaxLength attribute to limit the characters to 4.
<asp:TextBox ID="TextBox1" onkeyup="checkString(this, 'INT')" MaxLength="4" runat="server"></asp:TextBox>
<script type="text/javascript">
function checkString(inputID, inputType) {
if (inputID.value != "") {
if (inputType == "NUMERIC") {
validChars = "0-9,.";
} else if (inputType == "INT") {
validChars = "0-9";
} else if (inputType == "HASHTAG") {
validChars = "a-z0-9-_#";
} else if (inputType == "ALPHA") {
validChars = "a-z";
} else {
validChars = "a-z0-9";
}
var regexp = new RegExp("[" + validChars + "]+", "ig");
var matches = inputID.value.match(regexp);
if (matches == null) {
inputID.value = "";
} else if (matches.length != 0) {
inputID.value = matches.join("");
}
}
}
</script>

Related

Adding Comma seperator to the input field number displays as NAN

The commas are getting added correctly, but I'm getting this error message in the console:
"The specified value "NaN" is not a valid number"
I tried by making it as type="number", still the same warning.
jQuery(function() {
var extra = 0;
var $input = jQuery(".total_crm_records");
$input.on("keyup", function(event) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
if (event.keyCode == 38) {
extra = 1000;
} else if (event.keyCode == 40) {
extra = -1000;
} else {
return;
}
}
var $this = jQuery(this);
// Get the value.
var input = $this.val();
var input = input.replace(/[\D\s\._\-]+/g, "");
input = input ? parseInt(input, 10) : 0;
input += extra;
extra = 0;
$this.val(function() {
return (input === 0) ? "" : input.toLocaleString("en-US");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Input field : <input type="text" data-type="number" maxlength="20" class="total_crm_records">

Textbox Maxlength Issue for amount field

I have a situation having a textbox having 15 as a max length property. That field works as a amount field. it is working correctly in normal cases.
lets say if i enter 11234567890.99 this amount in textbox it displays it as 112,34,567,890.99 which is expected.
But, if i copy & paste 112,34,567,890.99 amount in textbox last two digits gets truncated because the length gets out of bound.
Is there any ways to change this without modifying the exact behavior? allowing to paste whole 112,34,567,890.99 amount.
$(document).on("focusout","#txtformate1",(function () {
if (this.value != null && this.value != "") {
$((this.parentElement).nextElementSibling).hide()
}
else{
$((this.parentElement).nextElementSibling).show()
}
}));
$(document).on('keyup', '.Amt', function () {
var val = $(this).val();
val = val.replace(/([~!#$%^&*()_+=`{}\[\]\|\\:;'<>,\/? ])+/g, '');
if(isNaN(val) && val!="-")
{
val="";
}
$(this).val(val);
/*if (isNaN(val)) {
val = val.replace(/(?!^)-/g, '');
if(val.indexOf("-")>-1)
{
val = val.replace(/[`*\/]/g, '');
}
else{val = val.replace(/[^0-9\.]/g, '');}
if (val.split('.').length > 2)
{
val = val.replace(/\.+$/, "");
}
else if(val==".")
{
val ="";
}
}*/
});
$(document).on('focusout', '.Amt', function () {
var val = $(this).val();
val = val.replace(/(?!^)-/g, '');
if(isNaN(val) && val.indexOf(',')>-1){
val=$(this).val();
}
if (val == "0.00"){
val="";
}
$(this).val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control Amt" id="txtformate1" maxlength="15" />`

Disable an asp net Button with javascript

I have a partial view where I would like to disable a button under certain conditions.
<td style="padding-left: 30px;">
<asp:Button ID="AddProdCostLine" runat="server" CausesValidation="False" Text="Add Line" CssClass="buttonBlue"></asp:Button>
</td>
In my javascript, I needed to check that some textboxes were filled, If not the user shouldn't be able to trigger the button (by disabling it)
In fact I need to set a textbox mandatory under the same conditions. That was my idea.
I can't find a way to disable my button here is the code :
function LoadComponentProdCost() {
$(function () {
$('input[id*="ProductionCostLineField"]').blur(function () {
var amount = this.value;
var textInInvoice = 'Mandatory';
$('input[id*="ProductionCostInvoiceToLineField"]').each(function () {
if (amount == '' || amount == '0') {
textInInvoice = '';
} else {
textInInvoice = 'Mandatory';
alert("You must inform the field 'Invoiced By'");
//doesn't work I need here to disable the button
document.getElementById("<%=AddProdCostLine.ClientID%>").disabled = "disabled";
document.getElementById('<%= AddProdCostLine.ClientID %>').disabled = true;
document.getElementById("<%=AddProdCostLine.ClientID%>").setAttribute("disabled", "disabled");
}
});
$('input[id*="ProductionCostInvoiceToLineField"]').val(textInInvoice);
});
});
My Javascript is in the partial view file .ascx
The rendered HTML for the component is like so :
<input name="ProdCostControl$ProdCostGrid$ctl02$ProductionCostInvoiceToLineField" type="text" maxlength="100" id="ProdCostControl_ProdCostGrid_ctl02_ProductionCostInvoiceToLineField" tabindex="25" style="width:269px;">
By using alert() function I managed to debug/check if my component was null so here is the solution to the code I post above :
function LoadComponentProdCost() {
$(function () {
$('input[id*="ProductionCostLineField"]').blur(function () {
var amount = this.value;
$('input[id*="ProductionCostInvoiceToLineField"]').each(function () {
var textInvoicedBy = this.value;
if (amount == '' || amount == '0') {
document.getElementById("<%=AddProdCostLine.ClientID%>").className = 'buttonBlue';
} else {
if (this.value != '' || amount == '' || amount == '0') {
document.getElementById("<%=AddProdCostLine.ClientID%>").className = 'buttonBlue';
document.getElementById('<%= AddProdCostLine.ClientID %>').disabled = false;
}
if ((amount != '' || amount != '0') && textInvoicedBy == '') {
alert("You must inform the field 'Invoiced By'");
document.getElementById("<%=AddProdCostLine.ClientID%>").className = 'buttonLightGray3';
document.getElementById('<%= AddProdCostLine.ClientID %>').disabled = true;
}
}
});
});
});
}

Creating a pattern for a number which must be prefixed by 3 letters eg (IKA111111)

function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );

Textbox allow only decimal numbers with dot using jquery

I have one textbox.It should be allow only decimal numbers and after dot only allow two digit(example 34545.43). how we can do it using jquery i have searched in google and stackoverflow but not satisfied answer because some script is not working in chrome and firefox. I tried but it is not working properly.So need help how to do it.http://jsfiddle.net/S9G8C/1685/
Js:
$('.allow_decimal').keyup(function (evt) {
var self = $(this);
self.val(self.val().replace(/[^0-9\.]/g, ''));
if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) {
evt.preventDefault();
}
});
This jQuery function will round the value on blur event of textbox
$.fn.getNum = function() {
var val = $.trim($(this).val());
if(val.indexOf(',') > -1) {
val = val.replace(',', '.');
}
var num = parseFloat(val);
var num = num.toFixed(2);
if(isNaN(num)) {
num = '';
}
return num;
}
$(function() { //This function will work on onblur event
$('#txt').blur(function() {
$(this).val($(this).getNum());
});
});
Number: <input type="text" id="txt" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can directly remove the 3rd digit when the user enters that.
var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
}
<input id="txtId" type="text"></input>

Categories

Resources