Reputation: 3651
I am trying to implement java code on a web based application to reduce redundancy and increase OOP principles
I have a phone validation regular expression on server side java code. I have a requirement to perform the same validation on the browser as people are adding information, without communicating with the server. I understand I can place the same code into the javascript but then I have two locations to maintain the same code. I am looking for a simple way to send the regular expression function with the http response.
//java code
Class myVerf
{
bool verPhone(input) {return //comepare verPhone to regEx}
}
//html
input type = "text" id = "1" onkeypress = "verPhoneFunc()"
//javascript
function verPhoneFunc()
{
//get value from id 1
//execute verPhone java code
}
Are there any downfalls to doing this? EX: what happens if there is no JVM on the machine the browser is running in? How does the java code execute on the browser?
I want to emphasise again... I cannot use AJAX because I can not communicate with the server.
Upvotes: 0
Views: 304
Reputation: 7519
If you are using Struts 2, for instance, you can leverage that framework's built in declarative validation mechanism. This supports declaration of validation in one location, and the framework propagates that validation to both server side validations and client side validations.
http://struts.apache.org/2.3.4.1/docs/validation.html
Upvotes: 1
Reputation: 9337
You can't easily and reliably share java code between your server-side app and the client app (like you said, what if there is no java installed; there are other reasons why this isn't a good approach as well).
Having said that, what you can do instead is share validation business rules. Define a language for specifying validation rules, then implement two validation engines that can read and execute these rules: one in Java for the backend and one in Javascript for the client. Your webapp can have a centrally managed repository of these rules and consistently feed them to both engines. The javascript engine can receive these rules embedded into the page's HTML, so no AJAX is necessary.
Upvotes: 1
Reputation: 676
There's not really a way to do what you're looking for, without some additional technologies.
The most direct way to do what you want is to prepare a string in some common location that both the Java and the Javascript can access it. For sake of discussion, I'll say this is in a textfile somewhere but if you're using (for instance) JSP, you could prepare the string in Java and publish it to Javascript via your JSP template. The string would contain the (uncompiled) regular expression.
In this solution you have retained your main design goal (keep the regex maintained in only one place.)
Upvotes: 2