Jan Desta Jan Desta - 5 months ago 13
PHP Question

Input fields in one form required for one submit button, but not for other?

How can I differentiate two separate actions for my submit buttons in one form, whereas one SAVES data into database (as is), and other submits form as a valid request, >>but<< according to HTML5 native validation (I use "required" attributes in HTML form)?

My form has 66 fields and I don't want to validate them all in PHP AFTER submission (as it's too cumbersome and time consuming), or validate them all in JS BEFORE submission (as I am not that agile in JS, as in PHP), so I use "required" and "type" attributes in HTML5, which is very convenient and quite versatile way of validation (besides older browsers).
However I cannot find a easy way to bypass the "required" attribute, when using save button, but not using "Send for submission" button. Can you help suggest a solution? I guess the prefered way is some JS/jQuery way, as I cannot determine which button would be used before hitting the button (so that I can make a field required or not).

Sample code:

<form>
A: <input type="text" name="A" required />
B: <input type="text" name="B" required />
C: <input type="text" name="C" />
<input type="submit" name="save" value="Save"> <!--do not require anything-->
<input type="submit" name="send" value="Send for submission"> <!-- require everything-->
</form>


Of course my form is huge, as it has 66 fields, so best solutions here are possibly general and versatile.

Answer

I've eventually come up with something like this. HTML:

<input type="submit" name="save" value="Save" onClick="removeRequired(this.form)">

JS (using jQuery):

function removeRequired(form){
    $.each(form, function(key, value) {
        if ( value.hasAttribute("required")){
            value.removeAttribute("required");
        }
    });
}

This is tested and working. It has this nice property, that I can keep the function elsewhere in files, to not clutch the php/html that is executing it. Only improvement I'd like (and probably other would be interested in) would be to eliminate jQuery as it's only used for browsing each input element in form, which seems easy enough for pure JS. However I could not find an easy way, and run out of time and used above with jQuery. Thanks