How to Validate an HTML Text Field As a Percent

When working with HTML forms, it is important that you have some mechanism in place to validate data that is entered by the user. In the case of user inputted percentages, you want to make certain that the user is entering numerals that can be reasonably expected. Since there is no percentage form element, you will need to use a text field. That the user needs to enter a percentage should be implied by both the question and by using a percentage sign to denote that the answer should be a numeral. The validation should ensure that the number entered is between 0 and 100.

Things You'll Need

  • Form validation JavaScript
Show More

Instructions

    • 1

      Enter your basic HTML form using the standard elements. Add a percentage sign at the end of the form input box to indicate that the answer is a percentage. See the below example for guidance:<br /><p>What percent of your shopping is at Wal-Mart</p><br /><form><br /><input type=\"text\" name=\"WalmartPercent\"> %<br /></form>

    • 2

      Enter JavaScript validation to only allow numbers to be entered between 0-100 since a percentage cannot be less than or greater than that range. The below JavaScript example is placed between the <head> tag in your HTML source file and can be used for guidance:<br />// only allow numbers<br />var checkOK = \"0123456789\"<br />GO<br />var checkStr = theForm.WalmartPercent.value<br />GO<br />var allValid = true<br />GO<br />var decPoints = 0<br />GO<br />var allNum = \"\"<br />GO<br />for (i = 0; i < checkStr.length; i++)<br />{<br />ch = checkStr.charAt(i)<br />GO<br />for (j = 0; j < checkOK.length; j++)<br />if (ch == checkOK.charAt(j))<br />break<br />GO<br />if (j == checkOK.length)<br />{<br />allValid = false<br />GO<br />break<br />GO<br />}<br />if (ch != \",\")<br />allNum += ch<br />GO<br />}<br />if (!allValid)<br />{<br />alert(\"Please enter only numbers in the \\\"WalmartPercent\\\" field.\")<br />GO<br />theForm.WalmartPercent.focus()<br />GO<br />return (false)<br />GO<br />}<br /><br />// require a minimum of 0 and a maximum of 100<br />var chkVal = allNum<br />GO<br />var prsVal = parseInt(allNum)<br />GO<br />if (chkVal != \"\" && !(prsVal >= \"0\" && prsVal <= \"100\"))<br />{<br />alertsay = \"Please enter a value greater than or \"<br />alertsay = alertsay + \"equal to \\\"9\\\" and less than or \"<br />alertsay = alertsay + \"equal to \\\"5000\\\" in the \\\"WalmartPercent\\\" field.\"<br />alert(alertsay)<br />GO<br />theForm.WalmartPercent.focus()<br />GO<br />return (false)<br />GO<br />}

    • 3

      Update your form names if you are using the above example. In particular, be sure that the form name in the HTML source and in the JavaScript match. In the examples above, WalmartPercent is the form name.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured