- Syntax: RegExpObject.test(string)
JavaScript: Test input fields for Valid Data
This JavaScript validates character input the user can enter into an input or textarea. This is useful in aiding the user enter the correct information such as a number or username.Complete Source code for the above example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > <head> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" /> <title>Check input fields for Valid Data</title> <script type= "text/javascript" > var numbersOnly = /^\d+$/; var decimalOnly = /^\s*-?[1-9]\d*(\.\d{1,2})?\s*$/; var uppercaseOnly = /^[A-Z]+$/; var lowercaseOnly = /^[a-z]+$/; var stringOnly = /^[A-Za-z0-9]+$/; function testInputData(myfield, restrictionType) { var myData = document.getElementById(myfield).value; if (myData!== '' ){ if (restrictionType.test(myData)){ alert( 'It is GOOD!' ); } else { alert( 'Your data input is invalid!' ); } } else { alert( 'Please enter data!' ); } return ; } </script> </head> <body> <h1>JavaScript: Test input fields for Valid Data</h1> <p>This JavaScript validates character input the user can enter into an input or textarea. This is useful in aiding the user enter the correct information such as a number or username.</p> <form name= "as400samplecode" action= "" method= "get" > <table> <tr> <td>Check for Numbers:</td> <td><input type= "text" id= "input1" maxlength= "30" size= "30" /> </td> <td><input type= "button" value= "Test" onclick= "Javascript:testInputData('input1',numbersOnly)" /></td> </tr> <tr> <td>Check for upto 2 Decimal:</td> <td><input type= "text" id= "input2" maxlength= "30" size= "30" /> </td> <td><input type= "button" value= "Test" onclick= "Javascript:testInputData('input2',decimalOnly)" /></td> </tr> <tr> <td>Check for Uppercase String:</td> <td><input type= "text" id= "input3" maxlength= "30" size= "30" /> </td> <td><input type= "button" value= "Test" onclick= "Javascript:testInputData('input3',uppercaseOnly)" /></td> </tr> <tr> <td>Check for Lowercase String:</td> <td><input type= "text" id= "input4" maxlength= "30" size= "30" /> </td> <td><input type= "button" value= "Test" onclick= "Javascript:testInputData('input4',lowercaseOnly)" /></td> </tr> <tr> <td>Check for String:</td> <td><input type= "text" id= "input5" maxlength= "30" size= "30" /> </td> <td><input type= "button" value= "Test" onclick= "Javascript:testInputData('input5',stringOnly)" /></td> </tr> </table> </form> </body> </html> |
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.