I am using jQuery Validate plugin to validate a "configuration page". I have a lot of inputs (like Name, Phone, Email...) and for last, "change password" section.

I have 3 inputs, like:

<label>Current password:</label>
<input name="current_password" type="password" id="current_password">

<label>New password:</label>
<input name="new_password" type="password" id="new_password">

<label>Confirm new password:</label>
<input name="confirm_new_password" type="password" id="confirm_new_password">

I want that:

If [current_password OR new_password OR confirm_new_password] are NOT filled, they are NOT required. (So the user would "submit" the page without changing his password).

But if ONE of them is filled, ALL them are required.

How can I do this?


I saw a similar question but the answer do not worked here, even with some changes, like:

required: function(element){ return $('#new_password').val()!="" },
有帮助吗?

解决方案

Try

var $cp = $('#current_password'),
    $np = $('#new_password'),
    $cnp = $('#confirm_new_password');

then

{
    rules: {
        current_password: {
            required: function () {
                return $np.val().length > 0 || $cnp.val().length > 0
            }
        },
        new_password: {
            required: function () {
                return $cp.val().length > 0 || $cnp.val().length > 0
            }
        },
        confirm_new_password: {
            required: function () {
                return $cp.val().length > 0 || $np.val().length > 0
            }
        }
    },
}

Demo: Fiddle

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top