Question

I am using jQuery plugin validation , i want to ignore the default values in a text box. i am addng cusotm validation in jQuery as follow. but it always return false. can any one help me what may be the issues in my code

$(document).ready(function () {
    $.validator.addMethod("defaultInvalid", function (value, element) {
        switch (element.value) {
            case "First Name":
                if (element.name == "First Name") return false;
        }
    });
    $("#frmReserv").validate({
        rules: {
            FName: "required defaultInvalid",
        },
        messages: {
            FName: "Please Enter Your Name",
        },
    });
});

And Html field is

<input type="text" value="First Name" name="FName"/>
Was it helpful?

Solution

This answer works in older versions of IE.


This is the custom method I've used in the past…

jQuery.validator.addMethod("defaultInvalid", function(value, element) {
    return value != element.defaultValue;
});

DEMO: http://jsfiddle.net/45J2Q/


To automatically hide/show the default text on focus/blur, add a class to the input and use this…

$('.autoclear')
.on('focus', function () {
    if ($(this).val() == $(this).prop('defaultValue')) {
        $(this).val("");
    }
})
.on('blur', function () {
    if ($(this).val() == "") {
        $(this).val($(this).prop('defaultValue'));
    }
});

HTML

<input type="text" value="First Name" name="FName" class="autoclear" />

DEMO 2: http://jsfiddle.net/45J2Q/1/

OTHER TIPS

Use HTML5 placeholder attribute

<input type="text" placeholder="First Name" name="FName"/>

than you don't need to make a check for default value.

$("#frmReserv").validate({
        rules: {
                FName: "required",
        },

Poyfill for placeholder https://github.com/mathiasbynens/jquery-placeholder

you can try this

<input type="text" placeholder="First Name" value="" name="FName"/>

Value="" will check at the time of jquery validation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top