Simple form validation script This is a simple form validation script.

I'd like to:


improve the jQuery validation
simplify the jQuery code


Questions:


Should I be exporting pure JS validation to avoid potential conflicts with other libraries that users might have installed?
Is it worth the effort or should I stick with my jQuery code?
Is there a way to reduce the chances for conflict with the jQuery code without having to reworking it to JS?




&lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
/*&lt;![CDATA[*/
$(document).ready(function() {

// when submit button is pressed
$("#form_name").submit(function() {

    var pass = true;

    var errors = {
        required    : 'this field is required',
        email       : 'enter a valid email address',
        numeric     : 'enter a number without spaces, dots or commas',
        alpha       : 'this field accepts only letters &amp;amp; spaces'
    };

    var tests = {
        email       : /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/,
        numeric     : /^[0-9]+$/,
        alpha       : /^[a-zA-Z ]+$/
    };

    // clear error messages
    $(".error").removeClass();
    $(".error-message").remove();

    function displayError(el, type) {
        $(el).parent().addClass("error").find('label').append('&lt;span class=\"error-message\"&gt; &amp;#8211; ' + errors[type] + '&lt;/span&gt;');
    }

    $('.required, .email, .numeric, .alpha').each(function(){
        var value       = $(this).val();
        var valueExists = value.length === 0 ? false : true;

        var required    = $(this).hasClass('required');
        var email       = $(this).hasClass('email');
        var numeric     = $(this).hasClass('numeric');
        var alpha       = $(this).hasClass('alpha');

        if (required &amp;&amp; value.length===0) {
            displayError(this,'required');
            pass=false;
        }

        else if (email &amp;&amp; valueExists &amp;&amp; !tests.email.test(value)) {
            displayError(this,'email');
            pass=false;
        }

        else if (numeric &amp;&amp; valueExists &amp;&amp; !tests.numeric.test(value)) {
            displayError(this,'numeric');
            pass=false;
        }

        else if (alpha &amp;&amp; valueExists &amp;&amp; !tests.alpha.test(value)) {
            displayError(this,'alpha');
            pass=false;
        }
    });

    return pass;
});
});
/*]]&gt;*/
&lt;/script&gt;
To avoid conflict with any other libraries, wrap your code using the jQuery function, and additionally call jQuery.noConflict();

The only conflict you may have is if somebody else imported an object named jQuery into the global namespace.

Reference: http://docs.jquery.com/Using_jQuery_with_Other_Libraries

Example:

jQuery.noConflict();
jQuery(document).ready(function($){
 //This is a jQuery function
 $('.myClass');
});