Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

adilsonb

Mascara de Entrada

Recommended Posts

Olá amigos

 

Estou tentando fazer funcionar uma mascara de entrada de data em javascript, no IE fuciona perfeitamente, mas no FF não..

 

Só preciso da máscara de entrada da data, já que no VS2005 usando webform não existe algo para fazer isso.

 

Postei a mensagem no forum de ASP.NET (Veja o tópico)

 

Como estou achando que o problema é de javascript, vou postar aqui..

 

<script type="text/javascript" language="javascript">	function init()		{		if(document.addEventListener) // DOM 2 Events compliant				{				document.getElementById(txtDate1ID).addEventListener("keypress", ValidateDate,  true);				document.getElementById(txtNumber1ID).addEventListener("change", ValidateNumber, true);				}		else// if(window.event)				{								document.getElementById(txtDate1ID).onkeypress = ValidateDate;				document.getElementById(txtNumber1ID).onchange = ValidateNumber;		};}function ValidateNumber(evt) {		var txtbox = null;		if(!evt && window.event) {			evt=window.event;			txtbox = evt.srcElement;			}		else txtbox = evt.target;		if (txtbox.value =="") return;		//this is a regular expression for 2 decimals postion		var re = /^(\+|-)?\d{1,6}(\.\d{1,2})?$/g;		if (!re.test(txtbox.value))			{				txtbox.style.borderBottom="maroon 1pt inset";				txtbox.style.borderRight="maroon 1pt inset";				txtbox.style.borderTop="red 2px outset";				txtbox.style.borderLeft="red 2px outset";				txtbox.style.textAlign="left";				var lbl= txtbox.parentNode.children[1];				if (!lbl) {					lbl =document.createElement("<span>");					txtbox.parentNode.appendChild(lbl);				}				lbl.innerText="* Invalid number";				lbl.style.color="red";			}		else			{				txtbox.style.textAlign="right";				txtbox.style.borderBottom="gainsboro 1pt groove";				txtbox.style.borderRight="gainsboro 1pt groove";				txtbox.style.borderTop="gray 2px outset";				txtbox.style.borderLeft="gray 2px outset";				var lbl= txtbox.parentNode.children[1];				if (lbl) {					lbl.innerHTML ="";				}							}	}	function ValidateDate(evt)	{		var ret=false;		var ValidationDateFormat = "01/01/1999";		var txt=null;		var txtEntered=null;		 var txtBox=null;		if(evt && evt.target) {						txt =  String.fromCharCode(evt.charCode);			txtBox =evt.target;			txtEntered = evt.target.value + txt;			}		else //if(event.keyCode )			{			txt =  String.fromCharCode(event.keyCode);;			txtEntered = window.event.srcElement.value + txt;			txtBox = window.event.srcElement;						}		  		//since I do not know what you will type next I am going to validate based on		//the assumption that further characters will be valid		var txtAssumedDate = txtEntered + ValidationDateFormat.slice(txtEntered.length);		//A regular expression to validate that the date is in the format MM/DD/YYYY		var re = /^(0[1-9]|1[0-2])\/([0-2]?\d|3[0-1])\/(1|2)\d{3}?$/g;		var CancelEntry=false;		if (re.test(txtAssumedDate))		{			ret=true;			re=/^(0[1-9]|1[0-2])$/g;						if (re.test(txtEntered))			{  				txtBox.value=txtEntered + "/";				//alert(txtBox.value);				CancelEntry=true;			}			re = /^(0[1-9]|1[0-2])\/([0-2]\d{1}|3[0-1])$/g;			if (re.test(txtEntered))			{  				txtBox.value=txtEntered + "/2006";				CancelEntry=true;			}		}		//if the assumed date matches the pattern		if (CancelEntry)		{			if (evt && evt.target)  evt.preventDefault();			else			{				event.returnValue=false;				event.cancelBubble = true;			}		}				return ret;	}	</script>	<div style="width: 750px;">		<h2>			Client-side validation of the TextBox server control</h2>		<p>			If I had to change the HTML objects on the browser based on validating the textboxes			input I would not use the Validation server controls. I would validate using regular			expressions and JavaScript on the client.		</p>		<p>			Below you should see 2 examples of validation; one that simulates the masked text			box for entering date. It would not allow you to type a character that does not			match the date format specified. The other would verify the number to be of 2 decimals.		</p>		<p>			To see the source code click on the link at the bottom of this section. For a more			advanced demo on using regular expressions click on the demo on the side menu titled			"Regular Expressions".		</p>		<table>			<tr>				<td>					Please enter a date in the following format only MM/DD/YYYY:					<asp:TextBox ID="txtDate1" runat="server" MaxLength="10" ></asp:TextBox>				</td>			</tr>			<tr>				<td>					Please enter a number with 2 decimals only					<asp:TextBox ID="txtNumber1" runat="server" ></asp:TextBox>				</td>			</tr>		  		</table>	</div>

Qualquer dica é bem-vinda.

 

Obrigado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

no lugar de postar o codigo com asp.net, manda o codigo html gerado pelo asp.net, pq assim fica + facil de testar no FF pra descobrir o problema

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá Wilker

 

Segue abaixo o código html gerado pelo asp.net, agradeço desde já pela ajuda.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head><title>	Untitled Page</title></head><body>	<form name="aspnetForm" method="post" action="teste.aspx" id="aspnetForm"><div><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJMzE1NDY4MjU1ZGRaDj9Gkpo9rJ8UUGuiRozsm9Pqng==" /></div>	<div>			<script type="text/javascript" language="javascript">	function init() 		{ 		if(document.addEventListener) // DOM 2 Events compliant 				{ 				document.getElementById(txtDate1ID).addEventListener("keypress", ValidateDate,  true); 				document.getElementById(txtNumber1ID).addEventListener("change", ValidateNumber, true); 				} 		else// if(window.event) 				{ 								document.getElementById(txtDate1ID).onkeypress = ValidateDate; 				document.getElementById(txtNumber1ID).onchange = ValidateNumber;		}; }  function ValidateNumber(evt) {		var txtbox = null;		if(!evt && window.event) {			evt=window.event;			txtbox = evt.srcElement;			}		else txtbox = evt.target;		if (txtbox.value =="") return;		//this is a regular expression for 2 decimals postion		var re = /^(\+|-)?\d{1,6}(\.\d{1,2})?$/g;		if (!re.test(txtbox.value))			{				txtbox.style.borderBottom="maroon 1pt inset";				txtbox.style.borderRight="maroon 1pt inset";				txtbox.style.borderTop="red 2px outset";				txtbox.style.borderLeft="red 2px outset";				txtbox.style.textAlign="left";				var lbl= txtbox.parentNode.children[1];				if (!lbl) {					lbl =document.createElement("<span>");					txtbox.parentNode.appendChild(lbl);				}				lbl.innerText="* Invalid number";				lbl.style.color="red";			}		else			{				txtbox.style.textAlign="right";				txtbox.style.borderBottom="gainsboro 1pt groove";				txtbox.style.borderRight="gainsboro 1pt groove";				txtbox.style.borderTop="gray 2px outset";				txtbox.style.borderLeft="gray 2px outset";				var lbl= txtbox.parentNode.children[1];				if (lbl) {					lbl.innerHTML ="";				}							}	}	function ValidateDate(evt)	{		var ret=false;		var ValidationDateFormat = "01/01/1999";		var txt=null;		var txtEntered=null;		 var txtBox=null;		if(evt && evt.target) {						txt =  String.fromCharCode(evt.charCode);			txtBox =evt.target;			txtEntered = evt.target.value + txt;			}		else //if(event.keyCode ) 			{			txt =  String.fromCharCode(event.keyCode);;			txtEntered = window.event.srcElement.value + txt;			txtBox = window.event.srcElement;						}		   		//since I do not know what you will type next I am going to validate based on		//the assumption that further characters will be valid		var txtAssumedDate = txtEntered + ValidationDateFormat.slice(txtEntered.length);		//A regular expression to validate that the date is in the format MM/DD/YYYY		var re = /^(0[1-9]|1[0-2])\/([0-2]?\d|3[0-1])\/(1|2)\d{3}?$/g;		var CancelEntry=false;		if (re.test(txtAssumedDate))		{			ret=true;			re=/^(0[1-9]|1[0-2])$/g;						if (re.test(txtEntered)) 			{   				txtBox.value=txtEntered + "/";				//alert(txtBox.value);				CancelEntry=true;			}			re = /^(0[1-9]|1[0-2])\/([0-2]\d{1}|3[0-1])$/g;			if (re.test(txtEntered)) 			{   				txtBox.value=txtEntered + "/2006";				CancelEntry=true;			}		}		//if the assumed date matches the pattern 		if (CancelEntry)		{			if (evt && evt.target)  evt.preventDefault(); 			else			{				event.returnValue=false;				event.cancelBubble = true;			}		}				return ret;	}	</script>	<div style="width: 750px;">		<h2>			Client-side validation of the TextBox server control</h2>		<p>			If I had to change the HTML objects on the browser based on validating the textboxes			input I would not use the Validation server controls. I would validate using regular			expressions and JavaScript on the client.		</p>		<p>			Below you should see 2 examples of validation; one that simulates the masked text			box for entering date. It would not allow you to type a character that does not			match the date format specified. The other would verify the number to be of 2 decimals.		</p>		<p>			To see the source code click on the link at the bottom of this section. For a more			advanced demo on using regular expressions click on the demo on the side menu titled			"Regular Expressions".		</p>		<table>			<tr>				<td>					Please enter a date in the following format only MM/DD/YYYY:					<input name="ctl00$ContentPlaceHolder1$txtDate1" type="text" maxlength="10" id="ctl00_ContentPlaceHolder1_txtDate1" />				</td>			</tr>			<tr>				<td>					Please enter a number with 2 decimals only					<input name="ctl00$ContentPlaceHolder1$txtNumber1" type="text" id="ctl00_ContentPlaceHolder1_txtNumber1" />				</td>			</tr>		   		</table>	</div>	</div>	<div>	<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwKv886PAwK0w4jnCwLJz/erBM6OnjbDqVlUSQsL1UQL64RiA120" /></div><script type="text/javascript"><!--var txtDate1ID='ctl00_ContentPlaceHolder1_txtDate1';var txtNumber1ID='ctl00_ContentPlaceHolder1_txtNumber1';init();// --></script></form></body></html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

eu vo dar uma olhada agora, mas me diz uma coisa, eu tb to mexendo com asp.net, e queria saber como você gero essas variaveis no final do codigo, essas:<script type="text/javascript"><!--var txtDate1ID='ctl00_ContentPlaceHolder1_txtDate1';var txtNumber1ID='ctl00_ContentPlaceHolder1_txtNumber1';init();// --></script>eu to mexendo em asp.net e nao sei faze isso, e as vezes preciso acessar o server controls e tenho um imenso trabalho...

Compartilhar este post


Link para o post
Compartilhar em outros sites

atualiza seu script ai fiote :P

 

eu mudei a funcao init, o problema eh q o FF nao consegue cancelar eventos usando o bind de eventos padrao... sim provavelmente um erro dele... e tb tive q mudar uma linha na funcao da data, pcausa de outro provavel bug do ff, o re.test(string) nao tava pegando direito, eu soh inverti, coloquei string.match(re) e pego de boa, e oa, n esquece de me dizer como você fez a parada de gravar o id de um server control numa variavel ;)

 

XD

 

<script type="text/javascript" language="javascript">	function init() {		document.getElementById(txtDate1ID).onkeypress = ValidateDate;		document.getElementById(txtNumber1ID).onchange = ValidateNumber;	}function ValidateNumber(evt) {		var txtbox = null;		if(!evt && window.event) {			evt=window.event;			txtbox = evt.srcElement;			}		else txtbox = evt.target;		if (txtbox.value =="") return;		//this is a regular expression for 2 decimals postion		var re = /^(\+|-)?\d{1,6}(\.\d{1,2})?$/g;		if (!re.test(txtbox.value))			{				txtbox.style.borderBottom="maroon 1pt inset";				txtbox.style.borderRight="maroon 1pt inset";				txtbox.style.borderTop="red 2px outset";				txtbox.style.borderLeft="red 2px outset";				txtbox.style.textAlign="left";				var lbl= txtbox.parentNode.children[1];				if (!lbl) {					lbl =document.createElement("<span>");					txtbox.parentNode.appendChild(lbl);				}				lbl.innerText="* Invalid number";				lbl.style.color="red";			}		else			{				txtbox.style.textAlign="right";				txtbox.style.borderBottom="gainsboro 1pt groove";				txtbox.style.borderRight="gainsboro 1pt groove";				txtbox.style.borderTop="gray 2px outset";				txtbox.style.borderLeft="gray 2px outset";				var lbl= txtbox.parentNode.children[1];				if (lbl) {					lbl.innerHTML ="";				}							}	}	function ValidateDate(evt)	{		var ret=false;		var ValidationDateFormat = "01/01/1999";		var txt=null;		var txtEntered=null;		 var txtBox=null;		if(evt && evt.target) {						txt =  String.fromCharCode(evt.charCode);			txtBox =evt.target;			txtEntered = evt.target.value + txt;			}		else //if(event.keyCode )			{			txt =  String.fromCharCode(event.keyCode);			txtEntered = window.event.srcElement.value + txt;			txtBox = window.event.srcElement;						}		  		//since I do not know what you will type next I am going to validate based on		//the assumption that further characters will be valid		var txtAssumedDate = txtEntered + ValidationDateFormat.slice(txtEntered.length);				//A regular expression to validate that the date is in the format MM/DD/YYYY		var re = /^(0[1-9]|1[0-2])\/([0-2]?\d|3[0-1])\/(1|2)\d{3}?$/g;		var CancelEntry=false;		if (txtAssumedDate.match(re))		{			ret=true;			re=/^(0[1-9]|1[0-2])$/g;						if (re.test(txtEntered))			{  				txtBox.value=txtEntered + "/";				//alert(txtBox.value);				CancelEntry=true;			}			re = /^(0[1-9]|1[0-2])\/([0-2]\d{1}|3[0-1])$/g;			if (re.test(txtEntered))			{  				txtBox.value=txtEntered + "/2006";				CancelEntry=true;			}		}		//if the assumed date matches the pattern		if (CancelEntry)		{			if (evt && evt.target)  evt.preventDefault();			else			{				event.returnValue=false;				event.cancelBubble = true;			}		}				return ret;	}	</script>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá Wilker

 

Funcionou no FF e no IE, muito obrigado! http://forum.imasters.com.br/public/style_emoticons/default/joia.gif

 

Estou tentando mudar para aceitar o formato dd/mm/yyyy mas não estou conseguindo, teria como de dar uma ajuda?

 

Tentei mudar a expressão regular, mas dai não valida mais.. :(

 

Agradeço desde já.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.