ewaldron
12-16-2003, 10:08 AM
I am trying to validate a form field with Javascript.the 1st 2 letters in the field have to begin with chars eg."CS" and the next four digits have to be numerical values eg."4557"
any ideas??
any ideas??
|
Click to See Complete Forum and Search --> : JavaScript Validation ewaldron 12-16-2003, 10:08 AM I am trying to validate a form field with Javascript.the 1st 2 letters in the field have to begin with chars eg."CS" and the next four digits have to be numerical values eg."4557" any ideas?? Geat 12-16-2003, 10:49 AM Use a regular expression of the form var myregExp = /[A-Z][A-Z][0-9][0-9][0-9][0-9]/; and use result = myregExp.test(document.formname.inputname.value); If this returns true, the input value is valid. ewaldron 12-16-2003, 11:35 AM Thanks, but i dont see how result is incorporated into the script. is "var myregExp = /[A-Z][A-Z][0-9][0-9][0-9][0-9]/;" Javascript syntax or are you trying to explain to me 2 chars-then 4 numbers?? how do i link the result variable to the myRegExp variable?? Geat 12-17-2003, 02:45 AM I'm not sure how familiar you are with the concept, but that bunch of characters is what's known as a regular expression - it's a way of matching patterns within a string. [0-9] means that the character must be a digit from 0 to 9, and [A-Z] means it must be a capital letter (if you want to use any letter, you can use [A-Z][a-z]). The full code you'd need is something like this: <SCRIPT> function checkForm() { var myregExp = /[A-Z][A-Z][0-9][0-9][0-9][0-9]/; if (!myregExp.test(myform.usercode.value)) { alert("Please enter a valid code"); return false; } else { return true; } } </SCRIPT> <HTML> <FORM NAME="myform" ONSUBMIT="return checkForm();"> <INPUT type="text" name="usercode"> <INPUT type="submit"> </FORM> </HTML> Jeff Mott 12-17-2003, 03:35 AM [A-Z][a-z]Note that this will not match any letter, it will match a capital letter followed by a lowercase letter. The expression can also be simplified with predefined character classes and quantifiers./^[a-z]{2}\d{4}$/i Geat 12-17-2003, 03:39 AM Touché, I meant [A-Za-z], but yeah - your purified way is better, if a little harder to read for newbies to the world of regular expressions. webdeveloper.com
Copyright Internet.com Inc., All Rights Reserved. |