I’m using a jquery script to validate form fields. This works well, but I’d like to change the validation of one field to check for IP Addresses.
The regex I want to use is :
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
How do I amend the below to work with this ? (This is how the validation works for email address)
jQuery("#Email").validate({
expression: "if (VAL.match(/^[^\\W][a-zA-Z0-9\\_\\-\\.]+([a-zA-Z0-9\\_\\-\\.]+)*\\@[a-zA-Z0-9_]+(\\.[a-zA-Z0-9_]+)*\\.[a-zA-Z]{2,4}$/)) return true; else return false;",
message: "Should be a valid Email id"
});
“\” characters are considered escape characters in javascript and should be doubled so it is interpretted literally as a “\” character. Quotation marks, also, must be escaped, though I see you have none present.
Applied to your regular expression, it would be:
In the context of your code, that would be then:
Notice that I left “^” at the beginning and “$” at the end, this means that you want the entire string to be matched by your regular expression I’m assuming. If that’s not the case, you should remove them. I haven’t tested if that regular expression does what you wish, but if it isn’t, you should be able to apply the rules written above to insert it into the code written above.
Edit: If you wish to do more advanced checks, such as determine if user was attempting an IP but failed or if it is something else entirely, then you could modify the expression code as follows:
Notice that the expression now calls existing function “isValidInput” and consequently the code is no longer an eval string, so all escapes have been removed. The 2nd match checks for
<number>.<number>.<number>+in an attempt to catch someone attempting to insert a valid IP (but apparently not doing a very good job of it). Hope that helps!