Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please Numbers Only:

I have four textbox within a form, I want to validate each of four textbox at a single button click. How I will do it, could anybody help me out for the same.

I have the code which has validated only one textbox value. Below is the code -

XML
<html>
<body>
<script type='text/javascript'>
function onlynumbers(element, AlertMessage)
{
 var regexp =  /^[-+]?[0-9]+$/;
if(element.value.match(regexp)) {
alert("Numbers Validation: Successful.");
return true;
}
else{
alert(AlertMessage);
element.focus();
return false;
}
}

</script>
<form>
Please Numbers Only:
<input type='text' id='txtnumbers'/>
Please Numbers Only:
<input type='text' id='txtnumbers'/>
Please Numbers Only:
<input type='text' id='txtnumbers'/>
Please Numbers Only:
<input type='text' id='txtnumbers'/>
<input type='button' onclick="onlynumbers(document.getElementById('txtnumbers'), 'Please Enter Numbers only.')" value='Validate Numbers'/>
</form>
</body>
</html>
Posted

1 solution

Javascript Code:
JavaScript
function onlynumbers(AlertMessage)
{
	var regexp =  /^[-+]?[0-9]+$/;
	var element;
        var counter = 0;
        var counter2 = 0;

	for (var i = 0; i < document.forms[0].elements.length; i++)
	{
		element = document.forms[0].elements[i];
		// For textbox only
		if(element.type == 'text')
		{
                        counter2 +=1;
			if(element.value.match(regexp)) {
				counter +=1;
			}
			else{
				alert(AlertMessage);
				element.focus();
				return false;
			}
		}
	}
        // Checking all textboxes are validated..
        if(counter == counter2)
        {
           alert("Numbers Validation: Successful.");
           return true;
        }
}


HTML Code:
HTML
<input type='button' onclick="onlynumbers('Please Enter Numbers only.')" value='Validate Numbers'/>
 
Share this answer
 
v3
Comments
Bittu14 2-Sep-15 13:55pm    
Hi Manas,
It has validated only one textbox..
Bittu14 2-Sep-15 14:00pm    
If i have set only one value in an one textbox, for others remains blank then only it has shown the success message.
[no name] 2-Sep-15 14:17pm    
I have changed code. Please try it again.
Bittu14 2-Sep-15 14:20pm    
Thanks.. It is working.......
Maciej Los 2-Sep-15 14:44pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900