What is the "Angular" recommended way to validate conditions that involve multiple fields on a form? Most or all of the validation examples that I have seen talk about custom validation directives that attach to a single textbox,select,etc. What about conditions that involve multiple fields on a form?
For example, I want to have an "empty" form validator: This will prevent submits on forms that have no required fields and all fields are empty.
Another example is, say I have a master/child one-to-many relationship on a page and the child relationship is a table of child records. What if I need to validate that at least one child record should exist IF 2 or 3 fields meet certain conditions?
One thought that I have is to built validation directives that attach to <form> tags as elements. Something like <form name="xxx" validate-not-empty > This directive will then set the $invalid property of the form, on submit. But I am concerned that this maybe is not the angular away to go as I have not seen this on any code samples I have seen. So I am looking for any alternatives to achieve this.
What is wrong with having your "not-empty" directive placed on each of your input field? (following this way of doing: http://angularjs.io/how-to-create-a-custom-input-validator-with-angularjs/)
Then you can just check anywhere if the form is valid, for example to disable the send button:
<button ng-disabled="!form.$valid">Send</button>
For it to work you must have all input with its ng-model.
I didn't quiet understand your master/child problem. It you could give an example...
I've used the basic validation, based on input type (email, tel, etc.) and the "required" attribute. But, more complex validation is typically handled through custom directives. Although, there may very well be a library that I'm not aware of that provides a common set.
As a basic example:
<form name="contactForm">
<input type="text" name="ContactName" ng-model="contact.name" required>
<button type="button" ng-click="submitForm(contactForm)" />
</form>
Then, in your controller:
$scope.submitForm = function (form) {
if (form.$valid) {
...
}
}
This W3Schools page describes Angular's validation fairly well.
AngularJS Form Validation
Toward the bottom of the article, they mention that custom validation requires a bit more effort. But, they provide examples.
To create your own validation function is a bit more tricky. You have
to add a new directive to your application, and deal with the
validation inside a function with certain specified arguments.
<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>
<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, mCtrl) {
function myValidation(value) {
if (value.indexOf("e") > -1) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$parsers.push(myValidation);
}
};
});
</script>
Hope this helps.
Related
I am struggling to figure out a way to trigger these AngularJS classes on a form I am trying to automatically fill with a chrome extension I am making. The form (specifically a textbox) has to be validated/modified before it will be validated and therefore submitted.
I originally tried using javascript to set the value of the textbox using the value property. This did not validate the form. I then tried using a dispatch event to send a key to the textbox, which resulted in nothing being input into the text box. How can I validate the form without requiring human input, or is this not possible?
Clarification, I am trying to replicate this action without user input by using a chrome extension.
Reference https://www.w3schools.com/angular/angular_validation.asp
Sounds like you need to create some events to simulate whatever angular is listening for, probably change or blur. Here's an example using click from mozilla:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events
function simulateClick() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var cb = document.getElementById('checkbox');
var cancelled = !cb.dispatchEvent(event);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
}
How can I validate the form without requiring human input
Get the forms controls:
var controls = $scope.tdForm.$getControls();
Trigger their validators:
controls.forEach( _ => _.$validate() );
From the Docs:
$validate();
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
For more information, see
AngularJS Form Controller API Reference
AngularJS ngModelController API Reference
When you type into the form, it updates the state of its controls (touched, dirty, etc.). According to how you define your fields validators (required, minLength...) the form will be valid or not after the user input.
In your submit method you should not proceed if any form fields are not valid. See AngularJS Developer Guide — Forms or Scotch Tutorials — AngularJS Form Validation you can have more details about AngularJS validation.
As Mike mentioned, you can use ngClass conditionally (see below) to apply some style classes only if a boolean condition occurr, for example the form is not valid.
<div ng-controller="ExampleController">
<form name="form" novalidate class="css-form">
<input type="text" ng-model="user.name" name="username" ng-class="{ 'error': !isValid }"/>
<div ng-show="form.$submitted>
<span ng-show="form.username.$error">Wrong Name</span></span>
</div>
<button ng-click="submit(user)"> Submit </button>
</form>
</div>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.isValid = true;
$scope.submit= function(user) {
if (user.name != 'Carl') {
$scope.isValid = false;
}
};
}]);
You can always programmatically change the form states if needed. For example to set the field to pristine:
$scope.form.$setPristine();
$scope.form.$setUntouched();
$setPristine sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class.
Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.
$setUntouched sets the form to its untouched state. This method can be called to remove the 'ng-touched' class and set the form controls to their untouched state (ng-untouched class).
Setting a form controls back to their untouched state is often useful when setting the form back to its pristine state.
UPDATE
Now it is clear what you are attempting to achieve. The two methods above can be used to set the form state, but if you want to validate it from code (this can be done passing the form to a service or directly in the controller for instance) then $validate() method will allow you to achieve that as mentioned by George.
I need to add client-side form validation to an HTML5 form. I don't want to hack my own solution and I'm not using Angular.
Since I'm using HTML5, the pattern and required attributes combined cover basic validation.
However, where custom validation is needed, for example, requiring a specific combination of checkboxes are ticked - I need something more.
A quick web search took me to The 10 Best JavaScript Libraries for Form Validation and Formatting.
I tested out Validate.js and hit a problem when validating checkboxes. Validate.js binds to specific form elements by name, e.g.
var validator = new FormValidator('example_form', [{
name: 'req',
rules: 'required'
});
The corresponding HTML form:
<form name="example_form">
<input name="req" />
</form>
I decided to apply this to a group of checkboxes AND implement my own custom rule (documented on Validate.js):
<form name="example_form">
<input type="checkbox" name="test" value="a">
<input type="checkbox" name="test" value="b">
<input type="checkbox" name="test" value="c">
</form>
Firstly, the Validator configuration object adding my custom rule:
var validator = new FormValidator('example_form', [{
name: 'test',
rules: 'callback_my_rule'
});
...notice the required rule (provided out-of-the-box) is gone, and has been replaced by my own rule callback_my_rule. Next I defined my_rule (as per the documentation, the callback_ prefix is dropped):
validator.registerCallback('my_rule', function(value) {
var atLeastOne = ($('[name="test"]:checked').length > 0);
return atLeastOne;
});
A return value of False means validation failed, whereas True is valid.
The problem is, if no checkboxes are ticked, my custom validation function, my_rule, is never called. Only when I tick a checkbox is the function called. It seems a unintuitive to only call custom validation functions when a checkbox is ticked.
The Validate.js documentation provides an example form with a checkbox, however, the checkbox validation function is omitted from the sample code:
However, the example form does validate the checkbox, digging around the source of Validate.js documentation, I see the checkbox uses the out-of-the-box required rule:
Questions
Has anyone got Validate.js working with checkboxes and custom
validation functions?
Is there a better library for custom form
validation?
I have tested Jquery Validation Plugin and works like a charm with checkbox!
DEMO LINK http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'inputname': {
required: true,
maxlength: 2
}
},
messages: {
'inputname': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
I am trying to add a custom validation function to Angular's ngMessages.
Specifically, I want the value of a few inputs (the number of inputs will be dynamic, but for now stick with 2) to total 100.
I have created a new directive called totalOneHundred which is triggering on a form change, but I cannot figure out how to access other form values from the link: call back.
I have posted my code below. Is there something I am missing? Also, if there is a better way to accomplish this (a sum() function in the controller and an ng-show, for example) please call me out.
Thanks for your help.
The form:
<!-- input box to be validated -->
<input type="number" class="form-control" name="lowBound" ng-model="ctrl.lowBound" total-one-hundred required>
<!-- validation messages -->
<div ng-messages="form['lowBound'].$error" role="alert">
<div ng-message="required">Cannot be empty</div>
<div ng-message="totalOneHundred">Sum of tasks must = 100</div>
</div>
<!-- input box to be validated -->
<input type="number" class="form-control" name="highBound" ng-model="ctrl.highBound" total-one-hundred required>
<!-- validation messages -->
<div ng-messages="form['highBound'].$error" role="alert">
<div ng-message="required">Cannot be empty</div>
<div ng-message="totalOneHundred">Sum of tasks must = 100</div>
</div>
The directive:
return {
restrict: "A",
require: ["^^form", "ngModel"],
link: function(scope, element, attributes, controllers) {
// At first, form is assigned the actual form controller...
const form = controllers[0];
const model = controllers[1];
model.$validators.totalOneHundred = function (modelValue, form, element, scope) {
// however, the value of form here is "1".
// modelValue is the value of the triggering input,
// but how can I access the other form inputs?
return true;
};
}
};
Initially I took your code and implemented this fiddle. A sum() method of the parent controller calculates the total (simple in the fiddle, but since the parent controller knows the entire, dynamic model, it is doable in the real case too). The total-one-hundred takes the sum as argument, i.e.:
<input type="number" class="form-control" name="lowBound" ng-model="ctrl.lowBound"
total-one-hundred="ctrl.sum()" required />
Alas, it doesn't work correctly! Problem: each input displays the "Sum of tasks must = 100" error. If you change a field and the total becomes correct, that field becomes valid and stops displaying the message. But the other fields do not!
EDIT: Well, it can work even this way. The secret is to add a watch on the sum for each validation directive and re-apply validation on that field; the new link function:
link: function(scope, element, attributes, controllers) {
const model = controllers[0];
var totalEvaluator = $parse(attributes['totalOneHundred']);
scope.$watch(totalEvaluator, function(newval, oldval) {
if( newval !== oldval ) {
model.$validate();
}
})
model.$validators.totalOneHundred = function (modelValue) {
return totalEvaluator(scope) === 100;
};
}
(NOTE that this costs an extra watch per field!)
Now however, the sum() function (which may potentially be expensive) is called many times. Watching the inputs of this function and calling it only when they change, may improve the situation.
An updated fiddle: https://jsfiddle.net/m8ae0jea/1/ (I still prefer model validation -see last paragraph- but it is good to be aware of all alternatives and their side-effects.)
This is a conceptual problem with cross-field validations. Where does the validation belong? If you can refactor your model so what gets validated is an entire object, then you can use Angular's custom controls as in this fiddle.
Now the model looks like:
this.model = {
lowBound: <a number>,
highBound: <a number>
};
And there is an editor for the entire model, complete with its own messages:
<model-editor name="entireModel" ng-model="ctrl.model" form="form"
total-one-hundred="ctrl.sum()"></model-editor>
<div ng-messages="form['entireModel'].$error" role="alert">
<div ng-message="totalOneHundred">Sum of tasks must = 100</div>
</div>
As you can see the total validation applies to the entire model.
The second example works correctly, if you can live with just a single message for the entire "total" validation. But I do not like it...
Angular's validation is (IMHO) a quick and dirty solution suited for simple things. Say a field must not be empty, another field must comply with a regular expression and so on. For complex things (like this case) I find it inappropriate to define business logic in the view. I prefer doing model validation and binding the validation results with Angular. To that extent, I created egkyron which is well suited for such things.
Or put in tl;dr code:
form.email.$setValidity('conflict', false);
is too sticky for my simple serverside validation flow.
I'm trying to get the form to show good feedback in the event that the user enters an email address already in use by another customer. I'm running AngularJS v1.2 and have this template:
<form name="form">
<input name="email" type="email" ng-model="..." required>
</form>
<div ng-messages="form.email.$error">
<div ng-message="conflict">Email address already in use.</div>
</div>
In my controller, I'll handle the submit event and trigger the validation in my $http.post().error handler like this:
$http.post('api/form/submit/path/here').error(function(resp) {
if (resp.details === 'conflict')
$scope.form.email.$setValidity('conflict', false);
});
The problem is that when the user goes back and changes the value in the input field, the error message doesn't go away. It sticks around until I manually call $scope.form.setValidity();.
The docs say implement a custom directive with an ng-model dependency, but that seems super overkill for my purposes. I've also tried setting $scope.form.email.$valid = false; and $scope.form.email.$invalid = true; but those don't change the appearance of the textbox.
Nothing in your code modifies the conflict validation key, except for when $setValidity('conflict', false) is explicitly called. Since that is the only code setting the state of the conflict validation key and there is nothing else resetting it to true, it's expected behaviour that editing the textbox wouldn't reset its conflict validation state.
To get the behaviour that you want, you need to code for it. One way is to use ng-change.
<input name="email" type="email" ng-model="..." required ng-change="resetConflictState()">
$scope.resetConflictState = function() {
$scope.form.email.$setValidity('conflict', true);
}
I am trying to find a simple solution to a required input type of scenario. I have multiple small forms that all send on one button save on the bottom of the page. What I am trying to accomplish is something like ngRequired, however across the whole controller, not just the individual forms. So the desired effect is pretty simple - if any of the inputs aren't filled out - set a boolean( or something) to false that disables the save button at the bottom.
So my first attempt is like this -
I have a model on each of the required items - there are 10 items
then I have a function that checks when you try to click the button how many are chcked like this
if($scope.modeltracker1){
//if there is anything inside model 1 add 1 to the tracker
$scope.modeltracker += 1;
}
and if the counter is not 10, don't do anything (all required are not filled out)
if($scope.modeltracker != 10){
//do nothing because all required are not filed out
}else{
//run save, all required all filed out
}
So - I feel like there should be a much easier solution than my first attempt here. Maybe something along the lines of checking if any individual one of these required fields is false, don't fire? I know that ngRequied would be great for this, but unfortunately the way this has to be structured, it cannot be one large form. There has to be a much easier way to accomplish this task with angular.
Any input would be much appreciated, thanks for reading!!
You can use ng-form to nest your multiple forms. It allows using nested forms and validating multiple forms as one form.
So, you need to nest your multiple forms in one root form.
<div ng-controller="demoController">
<form name="parentForm">
<ng-form name="firstForm">
<input type="text" ng-model="firstModel" required>
</ng-form>
<ng-form name="secondForm">
<input type="text" ng-model="secondModel" required>
</ng-form>
</form>
</div>
Then, all you need to do is to check parent form's validation status.
angular.module('formDemo', [])
.controller('demoController', ['$scope', function($scope) {
if($scope.parentForm.$valid) {
//run save, all required all filed out
} else {
//do nothing because all required are not filed out
}
}]);
you can use myForm.$invalid directive, as explained here: Disable submit button when form invalid with AngularJS