简体   繁体   中英

jQuery validate plugin, check input defaultValue

Trying to validate a field using jquery validate plugin. All I want to check if the current input value is not equal to defaultValue. If it is equal then its not valid, clean the value and show the error message.

Something like that:

...

firstname:{
    required: function(element){                       
    return element.val() !== element.defaultValue;
    element.val('');
    }                                          
}

...

Unfortunately that does not work.

Ok, found a solution. Simply creating a following method solves the issue.

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

Here's an implementation that works for radio buttons as well:

var isChanged = function ($element) {
    switch ($element.attr('type')) {
        case "radio":
            var $formElementsWithSameName = $element.closest('form').find(':input').filter(function () {
                return $(this).attr('name') == $element.attr('name');
            });
            return $formElementsWithSameName.filter(':checked').filter(function () {
                return $(this).prop('defaultChecked');
            }).length == 0;

        case "text":
            return $element.val() != $element.prop('defaultValue');
        default:
            console.error("No implementation of isChanged for element " + $element);
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM