ASP.NET - javascript - Asked By vadivu eagaraja on 08-Feb-12 08:36 AM

Hi all,

  for textbox control i've to validate such that it should not accept space as first char in between it can, code i use was below. how to modify this. help me to solve


<asp:TextBox ID="txtSortKey" runat="server" MaxLength="100" onkeypress="return check(event)" />



function

check(e) {

var keynum

var keychar

// For Internet Explorer

if (window.event) {

keynum = e.keyCode

}


// For Netscape/Firefox/Opera

else if (e.which) {

keynum = e.which

}

if (keynum > 31 && (keynum < 65 || keynum > 90) &&

(keynum < 97 || keynum > 122) && (keynum < 48 || keynum > 57) && (keynum!=32) ) {


return false;

}

else {

return true;

}

}


thanks in advance
by vadivukkarasi

Dilip Sharma replied to vadivu eagaraja on 08-Feb-12 08:54 AM
check the length of ur text box... 
if length is 0.. then not allow .. if it is greater then o ... Then allow space..
[)ia6l0 iii replied to vadivu eagaraja on 08-Feb-12 09:24 AM
Instead of all those keypress code for different browsers, you can take the first character and check if it is a space. I hope that makes your code readable. and hope that suffices your need as well.

string.char(0) will give you the first character in the string.

var sortKey= document.getElementById('txtSortKey').value;
   if(sortKey.charAt(0)==' '){
alert("Do not start with a space please.");
   }

Hope this helps.
Venkat K replied to vadivu eagaraja on 08-Feb-12 10:18 AM
Use  regular expressions:

String.prototype.ltrim = function() {
return this.replace(/^\s+/,"");
}
This function acts as a ltrim which remove all the spaces at the start of a string.
Thanks
vadivu eagaraja replied to [)ia6l0 iii on 08-Feb-12 11:49 PM

  hi ,
  that javascript code was common to all the textbox controls in the form... then how to achieve....

vadivu eagaraja replied to Dilip Sharma on 08-Feb-12 11:51 PM

  hi ,
  that javascript code was common to all the textbox controls in the form... then how to achieve....

Dilip Sharma replied to vadivu eagaraja on 09-Feb-12 01:30 AM

function

check(e,id) 

Here u can pass id of your text box also..

So it will work for every text box....

[)ia6l0 iii replied to vadivu eagaraja on 09-Feb-12 07:52 AM
Simple rule - If all textboxes follow the same validation (space as first character), then you should have the same function. If they don't then customize it. 

In the former case, you can use the sender argument to the function, and then retrieve the id attribute from it. 

function(obj)
{
  var id= $(object.target).attr('id');
}


Hope this helps.