In my application, I'm using form validation for many pages. If I want to focus on the invalid input element how to use without setting true or false in directive for every element.
<input type="text" ng-model="username" focus-me="isError"/>
In controller.js:
if(scope.username == "")
{
scope.isError = true;
}
Instead of using like the above code, is there any way to focus using ng-model?
You could use a blank ng-messages perhaps something like this, to trigger a method in your controller to set the focus:
<form name="vm.foo">
<input type="text" ng-model="username" id="fooUsername" />
<ul
ng-messages="vm.foo.fooUsername.$error"
ng-if="vm.validFormItem(vm.foo.fooUsername)">
<li ng-messages-include="some/validation/partial.html">
</ul>
</form>
Then the method inside your controller:
validFormItem(item) {
const returnValue = false;
// Do whatever checking you need in here to validate the form item
// to change returnValue;
// If it's false (not valid) then focus your form item here;
if (!returnValue) {
item.focus();
}
return returnValue;
}
I haven't tested this though.
Try something like
$('[ng-model="username"]').focus();
I'm searching to set validation for an input caused by angular-selectize directive (https://github.com/machineboy2045/angular-selectize).
The problem is that this directive:
<selectize config="pic.interGermConfig" options="pic.interGermOptions" data-ng-model="pic.interGermFilter"></selectize>
Produces this output:
<selectize config="pic.interGermConfig" options="pic.interGermOptions" data-ng-model="pic.interGermFilter"></selectize>
<div class=“selectize-control”>
<div class=“selectize-input items not-full”>
<div data-value=“value” class=“item”>Visual value</div>
<input type=“text” autocomplete=“off” placeholder=“” />
</div>
<div class=“selectize-dropdown multi”>
<div class=“selectize-dropdown-content”>
<div data-value=“value” data-selectable class=“option”>Visual value</div>
</div>
</div>
This tag:
<input type=“text” autocomplete=“off” placeholder=“” />
doesn't have ng-model directive property, so I can't use a custom directive with ngModel require, to set input validity.
Is it possible to do this in some way or is it possible sets input validity inside a controller rather that inside a directive?
Thanks
I find a solution for my needs, but I think this isn't the best way to do this.
In a first moment, I've tried to use $watch on model passed to selectize directive, but this it's not allowed because ng-model attribute is obscured and not propagated to the new DOM element when use selectize.
So, looking angular-selectize code, I've seen that directive allows to use ng-required attribute (https://github.com/ptesser/angular-selectize/blob/master/dist/angular-selectize.js).
So I've created a function to checks model and sets errors in the controller and then I've passed this function to ng-require.
<selectize config="pic.interGermConfig" options="pic.interGermOptions"
data-ng-model="pic.interGermFilter"
data-ng-required="pic.checkSelectizeRequire(pic.interGermFilter, 'germs')">
</selectize>
And this is the function
function checkSelectizeRequire(array, filter){
array = array === undefined ? [] : array;
if (array.length === 0){
vm.errorFilter[filter] = true;
}else{
vm.errorFilter[filter] = false;
vm.dirtyFilter[filter] = true;
}
}
To check errors in the form, I've created my own variables, because I don't know how check 'required' option for selectize input like classic way:
form.inputName.$error.required
Is there an easy way with parsleyjs to make a field required depending on another field?
See my js fiddle here http://jsfiddle.net/marksteggles/wbhLq0t4/1/
<form data-parsley-validate="true">
<div class="form-group">
<label>
<input name="request_signature" type="checkbox" />Require signature</label>
<div class="request_signature_fields">
<textarea class="form-control required" name="signature_reason" rows="3"></textarea>
</div>
</div>
<input class="btn btn-success" name="commit" type="submit" value="Send" />
</form>
Minimally as of 2.2.0 you can create a custom validator:
window.Parsley.addValidator("requiredIf", {
validateString : function(value, requirement) {
if (jQuery(requirement).val()){
return !!value;
}
return true;
},
priority: 33
})
This gets applied in such a way:
<textarea
class="form-control required"
name="signature_reason"
rows="3"
data-parsley-validate-if-empty="true"
data-parsley-required-if="#my-field-to-check"
></textarea>
Explanation
data-parsley-required-if is the custom validator we just defined. It takes any arbitrary jQuery selector and if that field contains a non-falsy value it ensures that this field is not empty.
data-parsley-validate-if-empty is needed to ensure that the field is being validated at all, because Parsley does not validate empty non-required fields by default.
More data on custom validators here: http://parsleyjs.org/doc/index.html#custom
There is no easy way yet (see this and this).
You can either toggle the attribute required with Javascript, or listen to the right parsley events on one field and check the other field.
Just incase anyone else is trying to work this out. The best way does seem to be altering the required attribute then clearing the values.
I used this:
HTML:
<input id="checkbox-id" type="checkbox">
<div id="conditional-inputs" style="display:none;">
<input type="text" name="somename" />
<input type="text" name="othername" />
<input type="text" name="onemoreforluck" />
</div>
jQuery:
$("#checkbox-id").change(function() {
if(this.checked) {
$('#conditional-inputs').slideDown();
/* use .slideDown to display conditional input block */
$("#conditional-inputs :input").prop('required', true);
/* set required attribute on all inputs inside conditional area */
}
else{
$('#conditional-inputs').slideUp();
/* use .slideUp to hide conditional input block */
$("#conditional-inputs :input").prop('required', false).val('');
/* remove required attribute on all inputs and empty values of inputs */
}
})
I realise that this question was asked and answered in 2012, and is most likely related to the ParsleyJS v1, while the most recent version at the time of writing this is v2.2.0. However I had to do some work on an old form that used v1 and I found that conditionals are possible (with a little bit of jQuery). So here's to anyone who might still need this.
You can dynamically add and remove form elements and constraints (read: validation rules) using the following:
$('#form').parsley('addItem', '#input_id');
$('#form').parsley('removeItem', '#input_id');
$('#input_id').parsley('addConstraint', '{ required: true }');
$('#input_id').parsley('removeConstraint', 'required');
So using jQuery listeneners for when the checkbox changes we can execute this kind of code which will add the signature field as a required field. Here it is in action for the question.
< script src = "js/parsley-v1.js" > < /script>
<script>
$('#request_signature').on('click', function() {
if($(this).is(':selected')) {
$('#signature_form').parsley('addItem', '#signature_reason');
$('#signature_reason').parsley('addConstraint', { required: true });
} else {
$('#signature_reason').parsley('removeConstraint', 'required' });
$('#signature_form').parsley('removeItem', '#signature_reason');
}
});
</script >
<form id="signature_form" data-parsley-validate="true">
<div class="form-group">
<label>
<input id="request_signature" name="request_signature" type="checkbox" />Require signature</label>
<div class="request_signature_fields">
<textarea id="signature_reason" class="form-control" name="signature_reason" rows="3"></textarea>
</div>
</div>
<input class="btn btn-success" name="commit" type="submit" value="Send" />
</form>
You can also hide the parts that are not required anymore, or disable the fields that are not needed, and add [disabled] and :hidden to the excluded Parsley option.
{
excluded: 'input[type=button], input[type=submit], input[type=reset], input[type=hidden], [disabled], :hidden',
}
NB: you don't need to hide each field, hiding a parent div is enough.
I found a good example that I forked here
➡️ http://jsfiddle.net/capripot/xoaLs4bt/
This should be possible with the great little Parsley addon plugin found here: http://themonk.github.io/parsely-conditions/
I found the shortest method -
$('input[type=radio][name=nlcsu]').change(function() {
// I am checking for a Radio button
if (this.value == 1) {
$("#nlcsu_post").attr('required', '1');
$("#nlcsu_year").attr('required', '1');
} else if (this.value == 0) {
$("#nlcsu_post").removeAttr('required');
$("#nlcsu_year").removeAttr('required');
}
});
What's the angular way to add validation rules to a form, that do not belong to a single input field, but on multiple field values together?
E.g.:
Check if at least one of x checkboxes is checked
Check if the sum of multiple number inputs is equal to a given Number
...
It would be nice if the errors can be shown with ng-messages. I'm using angular 1.3.10.
There's no built-in functionality, but it requires little effort.
ng-messages does not depend on anything specific. It just needs an object whose keys can be referenced by ng-message. The simplest solution would be to hook into the submit event (which you probably do anyway) and run additional validation.
<form ng-submit="post()" name="myForm">
<input type="checkbox" name="one" ng-model="one" />
<input type="checkbox" name="two" ng-model="two" />
<input type="submit" />
<div ng-messages="formErrors">
<p ng-message="tooMany">Please, check one checkbox only</p>
<p ng-message="required">Please, check a checkbox</p>
</div>
</form>
On submission the function post() is called which adds any error to the object formErrors:
$scope.post = function() {
...
var hasErrors = false;
$scope.formErrors = {
};
if ($scope.one && $scope.two) {
$scope.formErrors.tooMany = hasErrors = true;
}
if (!$scope.one && !$scope.two) {
$scope.formErrors.required hasErrors = true;
}
if (hasErrors) {
return;
}
}
By default, it seems that Angular reevaluates its binding from a particular DOM element (e.g Text Input) to the underlying scope property on keypress or paste - i.e, whenever the value in the text input changes.
Is it possible to make it only refresh the binding on blur? I.e. do something like:
<div ng-app>
<div ng-controller="ctrl">
<input type="text" ng-model="base" ng-update-type="blur"/>
<input type="text" />
<span ng-bind="doubled()" />
</div>
</div>
Take the following JS fiddle:
http://jsfiddle.net/f76dW/
I would like the doubled span to only update when I move the focus out of the first input
You can use ng-blur and a dummy variable (base_ in this case) to achieve that effect: http://jsfiddle.net/f76dW/1/
Template
<input type="text" ng-model="base_" ng-blur="updateBase()" />
Controller
function ctrl($scope) {
$scope.base = $scope.base_ = 1000;
$scope.updateBase = function () {
$scope.base = $scope.base_;
};
$scope.doubled = function() {
return $scope.base * 2;
}
}
Use ng-model options. Using a blur hack is tricky, because a blur may not be a change.
<input type="text" ng-model="a.b" ng-change="callScriptThenServer()" ng-model-options={updateOn: 'blur'}"/>