Using Form Validations with jQuery

Form validation is important for a list of reasons, anywhere from preventing unintentionally messing up a database to securing your system from malicious injection attacks, as well as the more mundane reasons such as making sure that the data entered makes sense. For example, a first name field probably shouldn’t permit special characters like $%&#@ or numbers.

Traditionally, you would use jQuery, or some form of JavaScript, to either mask a field or validate the data entered. The simplest example is to check that data has been entered for a required field:

if($(“#myInput”).val() !== ”){

// handle here

}

A note of caution: your carefully crafted validation is useless if end users turn off JavaScript features on their browsers. Data should be sanitized on both the server and client side before saving.

1. Feature Detection with Modernizr

Before going any further with HTML5 forms and jQuery, it’s a good time to mention the Modernizr library. It can greatly simplify the task of detecting browser features that aren’t yet implemented in all mainstream browsers. Modernizr does this by using a process called feature detection. Instead of relying on the old-school method of User Agent (UA) Sniffing, detecting a browser’s capabilities based on the unreliable navigator.userAgent string, feature detection tests for specific browser capabilities. This is a much more future-proof and user-friendly method of feature testing. It doesn’t matter if some new browser appears or some version of Chrome or Firefox hits the Web with a novel navigator.userAgent string. If the feature is supported, Modernizr will report it as being available.

For example, you could use Modernizer to detect if a browser supports the canvas element: In this sample, you’ll see one of the great features of Modernizr. For every feature it detects it stores a Boolean flag in the Modernizr object representing the result of the test. In this example, with supporting browsers, Modernizr.canvas will evaluate to true. In addition to this Modernizr also adds CSS classes to the html element indicating the availability of features.

<!DOCTYPE html>

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.6.1.js”></script>

<!– Link to modernizr, useful for feature detection –>

<script src=”http://ajax.cdnjs.com/ajax/libs/modernizr/1.7/modernizr-1.7.min.js”>

</script>

<script type=”text/javascript”>

if(Modernizr.canvas){

// code that depends on canvas here

} else {

// oops, canvas doesn’t exist, deal with situation

// here

}

</script>

</head>

<body>

</body>

</html>

Code snippet is from modernizr.txt

Anywhere I need to use Modernizr, we link to the code using the public JavaScript CDN ajax.cdnjs .com. Let’s put Modernizr to some use. Another great feature of HTML5 forms is the required field flag. For example, the following form:

<!DOCTYPE html>

<html>

<body>

<form>

<input type=”text” name=”userName” required/>

<input type=”password” name=”password” required/>

<input type=”submit” value=”send it” />

</form>

</body>

</html>

renders the message seen in Figure 6-1 in supporting browsers, in this case, Chrome, after attempting to submit a blank form.

Not all browsers support this feature, or even any of the other HTML5 features. Again, jQuery comes to the rescue for validating forms. As the following code illustrates you can use feature detection to determine if a browser has the “required field” feature, and if it doesn’t use jQuery techniques instead. Modernizr tests for the presence of the “required field” feature, and if it’s absent, a message div is appended to the document and a simple form handler is attached to the form. This handler tests to see if any of the required fields are empty using the jQuery form utility .val(). If one is empty it throws up the message div, adds a small border to the form field and prevents submission of the form. This is clearly a simplified form validation example, but it illustrates the basic concepts of form validation with jQuery and the basic concepts of using feature detection to take advantage of modern browser features.

<!DOCTYPE html>

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.7.1.js”></script>

<script src=”http://ajax.cdnjs.com/ajax/libs/modernizr/1.7/modernizr-1.7.min.js”>

</script>

<script type=”text/javascript”>

$(function(){

if( !Modernizr.input.required ){

var $msg = $( “<div id=’reqMessage’>Required Fields Missing</div>” );

$msg.css( “background-color”, “yellow” )

.hide();

$( “body” ).append( $msg );

$( “#fDet” ).on(“submit”, function(e){

$( “input[required]” ).each(function(){

if ( $(this).val() === “” ) {

$( “#reqMessage” ).show();

$( this ).css( “border” , “1px solid red” );

e.preventDefault();

}

});

});

}

});

</script>

</head>

<body>

<form id=”fDet” action=”#”>

<input type=”text” name=”userName” required/>

<input type=”password” name=”password” required/>

<input type=”submit” value=”send it” />

</form>

</body>

<html>

Code snippet is from featureDetection-form.txt

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *