MDBitz - Matthew Denton
HTML5
In addition to new tag elements in HTML5 the input element has been extended with new types and attributes. Although these changes are not fully supported across all browsers they can still be added if desired to your existing websites.
New input attributes
Placeholder Text
It is common practice to include placeholder or default text in form input fields. In most cases they simply describe what data should be entered and once a user clicks or focuses on the field the value is displayed. HTML5 specifications has added the placeholder attribute to input elements so that browsers will perform this function instead of having it performed by JavaScript. However until it is supported by all browsers you will still need to use JavaScript.
<form>
<input name="query" placeholder="Search" />
</form>
Auto Focus
You may in your websites be using a piece of JavaScript to focus a form field after a page has loaded. To make this task easier the autofocus attribute has been added.
<form>
<input name="name" autofocus />
</form>
New input types
The greatest thing about the input element is that if it doesn’t recognize the type (e.g. the browser doesn’t support the type) then it will default back to a text input field. That means that if you want to use any of the new input types like search and email then you can do so without worrying about missing form fields.
Search Input
In HTML5 it was decided to add a search type input. As you all know in your web pages you typically use a normal text type input for your search forms. However it was decided that the new search type should be added so browsers could add additional functionality to them to match the browsers search functionality. What this means is that each browser can do what they want with the field including changing the style to match the browser’s search so that it no longer is consistent with the rest of your web page.
<form>
<input name="query" type="search" />
</form>
URL & EMAIL Input
Both URLs and emails are strings that conform to respective Internet Standards. To make validation consistent and easier for developers the url and email type input elements have been added. The purpose of these fields is to verify and restrict the inputted data so only valid information is sent back to the server. However this validation would be performed at the browser level and if you are verifying other fields you will end up having to manage multiple error messages to the user which could be confusing to them.
<form>
<input name="email" type="email" />
<input name="website" type="url" />
</form>
Sliders and Spinboxes
Ever wanted to have simple easy to use slidebars or spinboxes when a user is inputting number values. In HTML5 your wish has been granted with the number and range input types. These elements allow you to set a minimum and maximum value as well as a step value for how it should be incremented. Again allowing the browser to display their version of sliders and spinbox controls and you not having to implement a JavaScript library to get your desired elements.
<form>
<input type="number" min="8" max="29" step="1" value="12" />
<input type="range" min="0" max="10" step="2" value="6" />
</form>
Calendar and Color Pickers
Commonly you will find yourself requesting that a user input a date or time and to handle this you will most likely include a JavaScript calendar to get your desired date picker. Similarly to number inputs, HTML5 adds support for input of various date types including month, date and time. These elements if supported by the browser would present a calendar interface for selecting a valid value. Less common but also specified is the color picker element defined by type color, however at this time no current browser supports the element.
<form>
<input type="color" />
<input type="date" />
<input type="time" />
</form>
HTML5 raises some developer complications and in my opinion is incomplete. The specifications outline the details on common elements currently created by JavaScript, however they do not specify how those objects are to be rendered. What this means is that it is up to the browser on how they are displayed and are no longer in the control of the designer/developer. In addition it introduces the concept of browser validation of input yet once again it doesn’t specify how the browser should handle the validation or how the designer/developer can tap into the validation. With complicated forms it is often the case that input is validated not only for standards but for required fields or custom data values, by including the new HTML5 elements you know have to worry about validation errors from your own scripts but also the browser and the multiple feedback could be confusing to your Users.
I understand that HTML5 is taking the first steps in expanding the common functionality of the web and it’s browser, however to make these new elements a viable choice for web developers/designers more specifications need to be detailed in how a browser is to behave. For example if you have a web form that is styled to match your site and the browser displays search input that doesn’t match your site then it won’t be used, same with calendars and color pickers. A good start definitely but don’t expect to see these elements commonly used for a while to come.
Resources
Calendar, color, Color Picker, Date, DateTime, eMail, Forms, HTML5, Input, MONTH, number, placeholder, time, url
MDBitz - Matthew Denton
Java
In the previous tutorial we walked through how to send email from a Java Application. This tutorial extends off that and explains how to send email from a SMTP server that requires basic User Authentication in the form of a user name and password. This is performed by use of the Authenticator object.
Prerequisites
This tutorial builds off of the previous example and as such you will need to review that tutorial to understand the requirements necessary to utilize the JavaMail API.
How to send an email from SMTP Server requiring User Name/Password Authentication
To get started lets build off of our MailUtil class we have already created by copying the class and refactoring it to BasicAuthMailUtil. For those who don’t know what refactoring is it means to rename the class.
After we have refactored the class our first step is to create our Authenticator object. Now we could do this by creating a separate class or creating an internal class. For our purposes we will create an internal class. To create an internal class you simply declare a class inside the class declaration of another class. We would do this by placing our BasicSMPTAuthenticator class stub before the closing } of our BasicAuthMailUtil class.
public class BasicAuthMailUtil {
/* existing code */
private class BasicSMTPAuthenticator
extends javax.mail.Authenticator
{
}
}
For our Authenticator to function we need to implement the getPasswordAuthentication method which will return to the caller a PasswordAuthentication object with the desired username and password
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( AUTH_USER, AUTH_PSWD );
}
You could replace the AUTH_USER and AUTH_PSWD values directly with the user and password information for the server or define them as variables of the BasicAuthMailUtil Class.
private static String AUTH_USER = "USER NAME";
private static String AUTH_PSWD = "PASSWORD";
Now that our Authenticator is created the last step is to initialize the session with our Authenticator. Therefore we will modify:
Session sess = Session.getInstance(props);
with the following which instantiates our Authenticator then obtains the Mail Session Instance based on the properties and Authenticator.
Authenticator auth = new BasicSMTPAuthenticator();
Session sess = Session.getDefaultInstance( props, auth );
Congratulations you now have a utility class that can send emails from a SMTP Server that requires user name and password authentication.
Resources
Authenticator, eMail, JavaMail API, PasswordAuthentication, SMTP, Tutorial
MDBitz - Matthew Denton
Java
Sending email from your java application is very straightforward when you utilize the JavaMail API. This library contains all the functionality necessary to connect to a SMTP Mail Server and send your email to its desired recipients. The next time you have an application performing some vital functionality instead of just logging an exception send an email to the administrator or development team so that the issue can be resolved right away.
Prerequisites
In order to use the javaMail API you need to obtain both the Java Mail and Activation Framework libraries which can be found at the following locations:
How to Send an Email
To send an email from java we must first start by importing the required classes into our MailUtil java class.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
After we have imported the necessary resources lets go ahead with the creation of our postMail function that will send and email with subject and message, to the specified recipients, cc recipients from the sender. Also it is important to note that we will be throwing any MessagingExceptions that occur so that the caller will be responsible for handling them as they see fit.
public static void postMail( String recipients[],
String subject, String message, String from,
String ccRecipients[] ) throws MessagingException {
}
Now that we have our method stub in place lets begin by initializing a Mail Session configured to our SMTP Mail Server. Please note that if you utilize logging in your application you can also set the debug mode to true to get useful information.
//Create Properties
Properties props = new Properties();
props.put( "mail.smtp.host", HOST );
props.put("mail.debug", "true" );
//Get Session
Session sess = Session.getInstance(props);
After our session is initialize we can go ahead with creating our email message.
Message msg = new MimeMessage( sess );
Populate the From email address by use of the InternetAddress class
msg.setFrom(new InternetAddress(from) );
We can populate the recipents of the message utilizing the setRecipients function. This function takes two parameters the Type of recipient and the array of recipients. So we would use Message.RecipientType.TO and Message.RecipientType.CC for To and CC recipients.
// recipients
InternetAddress[] addressTo =
new InternetAddress[recipients.length];
for( int i=0; i < recipients.length; i ++ ) {
addressTo[i] = new InternetAddress( recipients[i] );
}
msg.setRecipients( Message.RecipientType.TO, addressTo );
// ccRecipients
if( ccRecipients != null && ccRecipients.length > 0 ) {
InternetAddress[] addressCC =
new InternetAddress[ccRecipients.length];
for( int i=0; i < ccRecipients.length; i ++ ) {
addressCC[i] = new InternetAddress( ccRecipients[i] );
}
msg.setRecipients( Message.RecipientType.CC, addressCC );
}
After populating the recipients of the email we can set the subject and Date of the email
msg.setSubject(subject);
msg.setSentDate(new Date() );
Finally we set the content of the email. Please note that in most cases the text format will be text/plain for simple text emails or text/html for html formatted messages.
msg.setContent( message, "text/html" );
Now that our message is prepared we send utilizing the Transport class.
And that is how to send an email from your Java Application, The full source for the created Utility class can be found below. If your server requires Password authentication then you may be interested in the Advanced Tutorial.
Resources
eMail, How To, javax.activation, javax.mail, Tutorial
MDBitz - Matthew Denton
PHP
Email Validation is a tough subject to nail down, as their are tons of available code snippets that claim to validate an email address. To make it easier below you will find the requirements for a valid email address as outlined by RFC 2822 followed by a script that can be used to validate email addresses provided by linuxjournal.com.
Email Address Requirements
- An e-mail address consists of local part and domain separated by an at sign (@) character (RFC 2822 3.4.1).
- The local part may consist of alphabetic and numeric characters, and the following characters: !, #, $, %, &, ‘, *, +, -, /, =, ?, ^, _, `, {, |, } and ~, possibly with dot separators (.), inside, but not at the start, end or next to another dot separator (RFC 2822 3.2.4).
- The local part may consist of a quoted string—that is, anything within quotes (“), including spaces (RFC 2822 3.2.5).
- Quoted pairs (such as \@) are valid components of a local part, though an obsolete form from RFC 822 (RFC 2822 4.4).
- The maximum length of a local part is 64 characters (RFC 2821 4.5.3.1).
- A domain consists of labels separated by dot separators (RFC1035 2.3.1).
- Domain labels start with an alphabetic character followed by zero or more alphabetic characters, numeric characters or the hyphen (-), ending with an alphabetic or numeric character (RFC 1035 2.3.1).
- The maximum length of a label is 63 characters (RFC 1035 2.3.1).
- The maximum length of a domain is 255 characters (RFC 2821 4.5.3.1).
- The domain must be fully qualified and resolvable to a type A or type MX DNS address record (RFC 2821 3.6).
Validation Script
function validEmail($email) {
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex) {
$isValid = false;
} else {
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64) {
// local part length exceeded
$isValid = false;
} else if ($domainLen < 1 || $domainLen > 255) {
// domain part length exceeded
$isValid = false;
} else if ($local[0] == '.' || $local[$localLen-1] == '.') {
// local part starts or ends with '.'
$isValid = false;
} else if (preg_match('/\\.\\./', $local)) {
// local part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) {
// character not valid in domain part
$isValid = false;
} else if (preg_match('/\\.\\./', $domain)) {
// domain part has two consecutive dots
$isValid = false;
} else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) {
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) {
$isValid = false;
}
}
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))) {
// domain not found in DNS
$isValid = false;
}
}
return $isValid;
}
eMail, Validation
|
|