I have a text box that allow users to key in their desired unit,
and i would have to validate if this unit does exist.
Example 1: KM/H (Correct)
Example 2: KA/H (Wrong)
I know that emails address can be validated using codes like C#, JavaScript, Etc.
Is there any ways that I can validate (Units of measurement) through any codes, web service etc ? using Javascript, JSON?
P.s I am working on a JSP page :)
JavaScript is fully capable of validation (though it should not be used to validate at the expense of server-side validation, for security reasons). You can validate either by simple string checking (as below, which seems suitable to your case) or, for more complex, pattern-based validation, regular expressions.
Assumed HTML:
<form id='unit_form'>
<input type='text' name='unit' />
<input type='submit' value='go' />
</form>
Then, when the button is clicked (using jQuery...)
JS
$(function() {
var valid_units = ['KM/H', 'KM']; //etc...
$('#unit_form').on('submit', function() {
var unit = $('input[name=unit]').val();
if ($.inArray(unit, valid_units) == -1) {
alert('bad unit!');
return false; //cancel form submission
}
});
});
JS Fiddle
GNU publishes a nice little program called Units. It neatly does what you want.
Related
I test web application that uses HTML5 Constraint Validation API to generate error pop-ups.
How to verify text in the pop-ups in selenium tests?
I cannot find the appropriate locators.
The Selenium API doesn't support directly the constraint validation. However, you could easily get the state and the message with a piece of JavaScript (Java):
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement field = driver.findElement(By.name("email"));
Boolean is_valid = (Boolean)js.executeScript("return arguments[0].checkValidity();", field);
String message = (String)js.executeScript("return arguments[0].validationMessage;", field);
Note that it is also possible to use getAttribute to get the validationMessage even though it is a property:
String message = driver.findElement(By.name("email")).getAttribute("validationMessage");
as per your link provided sample HTML code snippet that address your problem is :
<form id="myForm">
<input id="eid" name="email_field" type="email" />
<input type="submit" />
</form>
i have gone through above html source and looked it very clearly ,but there is no html source code in the source code for validation message that generates after clicking on "Submit query".
However i can guide you throw a workaround that will work as good as if had worked when you have the error message.
Please understand that this way:
1.Please observer source code of input boxes with Constraint Validation API in HTML5?
2.you will clearly see that its attribute defines what type of data they can take in
our example attribute name and type.
3.they both clearly say that above html code will take input in the form of email only.
4.so your logic will be to check value entered in the input box is of the type of
email or not.if its email then pass the test otherwise fail.
Hope this make sense top you and eventually helps you.
My current project has me accessing a database quite frequently. To do so, I make calls to my Java Servlet through jQuery Get and Post calls. I was wondering if it was better practice to build any HTML using the data I gather from the database within the servlet before I ship it back to the jQuery or if I should do the HTML injecting with JavaScript alone? For example, let's say I have a database table with a user ID and a username. If I wanted to create a select box off this table, which would be the better way? Or is there even a better way? Would it be better to just try send the rawest form of the data retrieved from the database from the servlet to the JavaScript, allowing it to handle all of the HTML formatting?
Method 1 (Java)
Given the Following HTML/JavaScript
<html>
<head>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get("servlet?cmd=getUsers", function(data) {
$("#select").html(data);
}, "html");
});
</script>
</head>
<body>
<div id="select"></div>
</body>
</html>
Using The Following Servlet
PrintWriter writer = response.getWriter();
response.setContentType("text/html");
writer.println("<select id='userSelect' name='user'>");
while(resultSet.next()) {
String userId = resultSet.getString("ixUser");
String userName = resultSet.getString("sName");
writer.println("<option value='" + userId + "'>" + userName + "</option>");
}
writer.println("</select>");
Method 2 (JavaScript)
Given the Following HTML/JavaScript
<html>
<head>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.get("servlet?cmd=getUsers", function(data) {
$("#select").html("<select id='userSelect' name='user'>");
$(data).find("user").each(function() {
var id = $(this).find("id").text();
var name = $(this).find("name").text();
$("#userSelect").append("<option value='" + id + "'>" + name + "</option>");
});
$("#select").append("</select>");
}, "xml");
});
</script>
</head>
<body>
<div id="select"></div>
</body>
</html>
Using the Following Servlet
PrintWriter writer = response.getWriter();
response.setContentType("text/xml");
writer.println("<xml>");
while(resultSet.next()) {
String userId = resultSet.getString("ixUser");
String userName = resultSet.getString("sName");
writer.println("<user>");
writer.println("<id>" + userid + "</id>");
writer.println("<name>" + userName + "</name>");
writer.println("</user>");
}
writer.println("</xml>");
I'd opt for sending raw (well, JSON) data to the client and have Javascript take care of the templating. Why?
Separation of concerns: Your server code shouldn't be aware of the presentation logic.
Less bandwidth: If you can save a few k/request (at least), why not?
It seems that the world is moving towards your second approach. There are several reasons for this:
Your users will perceive that your application is more responsive than it actually is because the page will be loaded in parts, so there is always progress being made (or at least a progress indicator if there is something that takes a long time to load).
You can re-use the data services for additional clients other than your website (think native mobile apps).
The data format is almost always more compressed than the html that is generated, so you send less data over the wire. I would actually recommend json over xml for this reason.
The javascript engines in most browsers are much more efficient than they were a few years ago. This allows you to offload some of the more complex page layout logic from your server, making your application more scalable.
It will be easier to test that the data returned is correct without having to wade through the formatting html to access it.
I'd suggest returning only the data in a lightweight manner such as JSON.
My reasons:
Bandwidth
Smaller data to be cached when performance concerns come into play
Flexibility. If you wanted to expose this data to another part of your application or a mobile device?
There are several other methods but in my mind this is a much more organized approach. Let the client deal with the markup processing.
I would suggest jQote2 as an awesome client side templating tool. (It's just awesome!)
These days the cool kids do MVC on the browser. -- Your method 2, but a more sophisticated client-side stack.
In other words, your server exports an api that provides data, not html.
Then, on the browser, your JS app has separate Model, View and Controller code. See the Backbone project for the Model and Controller layer, Mustache for the View/Template layer. An article. Another post.
method 1, as you are not comfortable enough with method 2.
a few words on method 2.
choose between string concatenation, or object building.
var html = '<select...
...
html .= '</select>';
$("#select").append(html);
or
var $sel = $('<select>').attr('id', 'userSelect').attr('name', 'user').
as you see, $('<tag>') syntax creates a new dom element.
Moreover, return a json object instead of xml if you can. They are more easy to work with in javascript.
So you can do
for (i in data) {
$('<option>').text(data[i].name).val(data[i].id).appendTo($sel);
}
$("#select").append($sel);
And then, there is method3: templating...
Traditionally we have always used xml in the response which is parsed by a Javascript method to execute post processes. I came up with a new, simpler implementation which uses a hidden input set by a requestAttribute and executed in an ajax callback.
JSP:
<%
String jsPostProcess = (String)request.getAttribute("jsPostProcess");
if (jsPostProcess!=null && jsPostProcess.trim().length()>0){
%>
<input type="hidden" id="jsPostProcess" name="jsPostProcess"
value="<%= jsPostProcess %> "/>
<% } %>
AJAX CALLBACK:
var callback = {
success: function(response) {
var div = $(divId);
if (div){
div.innerHTML = response.responseText;
}
var jsPostProcess = $('jsPostProcess');
if (jsPostProcess)
eval(jsPostProcess.value);
},
failure: function(response) {
alert('Something went wrong!');
}
}
SERVLET CODE:
request.setAttribute("jsPostProcess", jsPostProcess);
It works beautifully, and it is so much simpler for adding js post processes to virtually any call no matter how simple or complex the functionality is. No need for customized js methods for parsing.
Curious if anyone could identify any potential problems with it (such as security issues?) or make any suggestions for other alternatives. We currently use Prototype and YUI 2 on the front-end.
First, there's no need for that unpleasant scriptlet code:
<c:if test='${not empty jsPostProcess}'>
<input type='hidden' id='jsPostProcess' name='jsPostProcess' value='${jsPostProcess}'>
</c:if>
Next thing is that I hope that somewhere before this point the "jsPostProcess" value has been scrubbed so that it doesn't break the markup (like, in case it includes quotes).
Just calling eval() on the value like that seems a little dangerous, though perhaps you know pretty well what it's going to be.
Finally I would offer the suggestion that as an alternative to that, if the "post process" code isn't too big you could send it back in a response header. Then you wouldn't have to drop any meaningless markup into your page.
Oh, also finally: you might want to make the <input> be disabled. Or, alternatively, you don't even have to use an input: you can use this trick:
<script id='jsPostProcess' type='text/plain'>
${jsPostProcess}
</script>
Because the "type" attribute is "text/plain" the browsers won't try to execute that code, and you can get the "text" of the <script> element whenever you want.
I am trying to create a form for my company's website. I am letting a customer selectively donate to my company upon download of a piece of software. If they check a box, I'd like a "Donate" button to appear with code to go to my third party store (I know how to do this), and if they don't select the checkbox, then I'd like a different button to appear that will link them to the download of the software (I also can do this).
I would prefer to stick to PHP, Javascript, and HTML. I do not have immediate access to anything like asp.net.
Thanks!
Yes. Just toggle the value of button.style.display between 'none' and '' with JavaScript.
<input id="my_check_box" type="checkbox" onclick="handleCheckChange()" onchange="handleCheckChange()" />
<input id="my_donate_button" type="submit" style="display: none" value="Donate now!" />
<script type="text/javascript">
function handleCheckChange() {
var my_donate_button = document.getElementById("my_donate_button");
if (document.getElementById("my_check_box").checked) {
my_donate_button.style.display = '';
} else {
my_donate_button.style.display = 'none';
}
}
// Browsers may pre-check the box if the user re-loads the page,
// so call this to make sure the page is consistent.
handleCheckChange();
</script>
ya u can do it..
create a javascript function named like
function check_button()
{
if(document.getElementById('checkbox_id').value=="checkbox_value")
{
document.getElementById('button_id').style.display="block";
}
else
{
document.getElementById('button_id').style.display="none";
}
}
call this function in checkbox html code
This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 6 years ago.
I am new to JSP and related technologies. I need to write a JSP form with some required fields (including Captcha), the form will require validation. Upon successful submission of the form, it should be able to email to a stated email address which is grabbed/parsed from a .txt file.
That is basically the flow. But technically how should I do it in JSP/java? Is there any good tutorial referencing to my above form requirement? How should I be able to grab/parse the text file. And lastly,
I remembered that php has a function called mail() to do the emailing, how should I do it in jsp?
Thank you very much.
JSP is just a view technology providing a template to write client side markup/style/scripting languages in, such as HTML/CSS/JS code, alongside with the possibility to control the page flow dynamically with help of taglibs such as JSTL and access to backend data with help of EL. In your speficic case a plain vanilla HTML form would already suffice.
<form action="servletname" method="post">
<input type="text" name="foo"><br>
<input type="text" name="bar"><br>
<input type="submit"><br>
</form>
To control, preprocess and/or postprocess the request and response, the best way is to use a Servlet. Basically just extend HttpServlet and implement the doGet() to preprocess data or the doPost() to postprocess the data. The servlet can be mapped on a certain url-pattern in web.xml. The HTML form action URL should match this url-pattern.
If you want to make use of the very same form to redisplay the submitted page and any error messages, then you can just make use of EL:
<form action="servletname" method="post">
<input type="text" name="foo" value="${param.foo}" ${not empty messages.succes ? 'disabled' : ''}>
<span class="error">${messages.foo}</span><br>
<input type="text" name="bar" value="${param.bar}" ${not empty messages.succes ? 'disabled' : ''}>
<span class="error">${messages.bar}</span><br>
<input type="submit">
<span class="succes">${messages.succes}</span><br>
</form>
Where ${messages} is basically a Map<String, String> which you've put in the request scope in the servlet. For example:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
if (foo == null || foo.trim().isEmpty()) {
messages.put("foo", "Please enter this field");
}
if (bar == null || bar.trim().isEmpty()) {
messages.put("bar", "Please enter this field");
}
if (messages.isEmpty()) {
YourMailer.send(createTemplate(foo, bar), mailto);
messages.put("succes", "Mail successfully sent!");
}
// At end, forward request to JSP page for display:
request.getRequestDispatcher("pagename.jsp").forward(request, response);
}
More about JSP/Servlet can be found in Java EE 5 tutorial part II chapters 4-9 and in Marty Hall's Coreservlets.com tutorials. To go a step further you can always abstract all the boilerplate stuff (request parameter retrieval, value conversion/validation, event handling, navigation, etcetera) away with help of any MVC framework which is built on top of Servlet API, like Sun JSF, Apache Struts, Spring MVC, etcetera.
With regard to captcha's, you can just use any Java Captcha API to your taste and follow the instructions. Often they have their own servlet/filter which stores a key/toggle/signal in the request or session scope which determines whether the captcha did match or not. You can just access its outcome inside your servlet.
With regard to mailing, you can just use any Java mail API to your taste, however the choice is only limited to the great JavaMail API and the more convenienced one provided by Apache which is built on top of JavaMail API.
That's a lot of questions in one question; here are a couple links which might be helpful (i.e., we've used them in the past):
Kaptcha: http://code.google.com/p/kaptcha/
JavaMail: http://java.sun.com/products/javamail/
Try using skeleton app AppFuse. It offers different frameworks from the basic to advanced ones. Here's an article on captcha integration.