Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - can I validate a disabled field?

I've got a form where the user needs to click a link, select a user via a popup window which then populates a hidden field with an ID and a display field with the username.

The display field is set to disabled="disabled" to force the user to use the popup and not type a value in the field.

I need to ensure the user selects a name. I'm using jQuery and Jorn's validation plugin.

Doing a required: true on the disabled field doesn't seem to fire off if the value is blank.

Any ideas how to solve this?

like image 542
Jim Priest Avatar asked Jul 25 '10 16:07

Jim Priest


People also ask

How check textbox is disabled or not in jQuery?

You can use $(":disabled") to select all disabled items in the current context. To determine whether a single item is disabled you can use $("#textbox1").is(":disabled") . Save this answer.

Does jQuery validate require a form?

The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

What is remote validation in jQuery?

According to the jQuery validate documentation for remote: The response is evaluated as JSON and must be true for valid elements, and can be any false, undefined or null for invalid elements, using the default message; or a string, eg. "That name is already taken, try peter123 instead" to display as the error message.

What is validator addMethod in jQuery?

addMethod( name, method [, message ] ) Description: Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a javascript based function and a default string message.


2 Answers

Instead of making it disabled, have you tried making it readonly?

<input type="text" readonly="readonly" />

I remember from years ago that disabled fields are not submitted by forms, and hence probably are not validated

Here is the W3C HTML4 Spec on the topic.

like image 58
naikus Avatar answered Sep 29 '22 12:09

naikus


According to the previous suggestion the possible solution could be:

var _valid = $.fn.valid;
$.fn.valid = function (alsoDisabled) {
    var alsoDisabled = alsoDisabled || false;
    if (alsoDisabled) {
        this.find('[disabled]').prop('disabled', false);
    }
    var retVal = _valid.apply(this);
    if (alsoDisabled) {
        this.find('[disabled]').prop('disabled', true);
    }
    return retVal;
};


and so you could call the valid method with the optional arguments: $('#form').valid(true) to check also disabled field or $('#form').valid() for the normal behaviour

best regards Gaetano

like image 33
Gaetano Avatar answered Sep 29 '22 14:09

Gaetano