2

I have an input that is optionally disabled. When disabled it still seems to take part in form validation. How can I remove this input from form validation?

<form ng-app name="myForm">
    <label>Name</label>
    <input type="text" name="name" ng-model="form.name" ng-disabled="show" required>
    <input type="submit" ng-disabled="myForm.name.$invalid">
    <input type="submit" ng-click="show = !show" value="Toggle">
</form>

Notice on the example that when you hit toggle the input is disabled but the Submit button does not become enabled.

1
  • This is one of the reasons I don't like the form validation approach in Angular (although not specific to Angular, it is encouraged), in more complex scenarios you're going to end up with logic bleeding in to the markup. I'd consider moving all of your validation logic in to the model and out of the UI. github.com/nadavsinai/ndValidation is a directive which you can use, I've also outlined my preferred way of doing it here: northerncodemonkey.wordpress.com/2014/11/26/… although haven't managed to get it onto GIT yet. Commented Dec 5, 2014 at 9:07

2 Answers 2

1

You can use ng-required in this case :

<form ng-app name="myForm">
    <label>Name</label>
    <input type="text" name="name" ng-model="form.name" ng-disabled="show" ng-required="!show">
    <input type="submit" ng-disabled="myForm.name.$invalid">
    <input type="submit" ng-click="show = !show" value="Toggle">
</form>
Sign up to request clarification or add additional context in comments.

3 Comments

This works in the demo but, when I have a custom directive applied doesnt work.. How can I make this work with a custom directive?
@Chris it depends on how your directive is written, to get this functionality your directive should also support to be disabled. Global ways that always work I don't know directly. Ofcourse there should be a possibility to write a directive that always triggers a valid on a field when true.
I ended up doing this in the directive to select if it was required or not, based on your original answer, thanks. if (ele.attr("required") == "required") { }
0

You can do it with pure JavaScript. By searching for the attribute you created.

function validateForm() {
    var inputElements = document.forms["myForm"].getElementsByTagName("input");
    for(inpt_ele=0; inpt_ele<inputElements.length; inpt_ele++) {
        if(inputElements[inpt_ele].getAttribute("disabled") == "disabled") {
            //skip
        }
        else {
            //validate
        }
    }
}
validateForm();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.