Custom validation on Angular Form - on blur - javascript

In Angular, I am trying to validate a value of a field on blur. I have a list of customers, and I want to check if the model value in the field is in my list of customers. If not, I want to set the validity to false.
I know that ng-model-options="{updateOn: 'blur'} exists, however, I can't use this because the field is a typeahead so it must update based on the model. The validation is what needs to happen on blur.
The answer seems to be:
Write it as a function in the controller and use $setValidity just as you would in a directive. Use ng-blur to trigger the function in the input field.
-However, I keep running into examples where a custom validation (make the field invalid if the model value does not match one in the list) is only written as a directive. Are there examples of custom validation written as a function?
Write a directive that only triggers on blur.
However, I can't find examples that do either of these things. Does anybody have an example of custom validation as a function OR a directive that only updates on blur of the field?
I found this link very helpful for custom validation but I still have the same problem with the difference between a function and a directive: How to add custom validation to an AngularJS form?

As something we've been working on recently:
<form name='vm.formName' id='vm.formName' novalidate>
<input type='text' id='textField' name='textField' ng-blur='vm.blurMethod()' ng-model='vm.model.text' />
// The submit is only here for show;
<input type='submit' id='submit' ng-click='vm.submitForm()' />
</form>
In the controller:
blurMethod() {
if (this.formName.textField.$viewValue !== myArbitraryValue) {
// $setValidity called on the form, setting the textfield's validity to false
// then you can have your own validators show the error in the template
this.formName.$setValidity('textField', false);
}
}
That's off the top of my head, will take a look in the morning to see if it mirrors what we've been using. Updated the $setValidity call now.
This assumes you're using the controllerAs: 'vm' syntax, which is why the form has a name 'vm.formname' and the controller is using 'this'.

I have used ui-bootstrap for typeahead with plenty of control on your validation ui-bootstrap typeahead
EDIT- Code sample
<input type="text" ng-model="selected"
typeahead="state for state in states | filter:$viewValue | limitTo:8"
class="form-control"
typeahead-no-results="$scope.matchFail">
<div ng-show="$scope.matchFail">Not on list!!</div>
When you choose a value that is not on the list, the div is displayed

Related

Alphanumeric String Validation in Angular 6

I need to validate user input with below validations and shoulw not allow user to submit the form untill the validation error messages are cleared
Below are the validations my code need to perform.
1)String will be a alphanumeric.
2)String Length should not be more than 7
3)String should be either of theses patterns "w123456"(w followed by 6 numbers) or "df12345"(df followed by 5 numbers)
Can someone help me how to validate this?
Contact: <textarea required ngModel name="contacts" #contacts='ngModel' placeholder="Enter Valid contactid" ngModel name="contacts" #contacts="ngModel" rows="10" cols="15"></textarea>
I've provide a JSFiddle link below.
https://jsfiddle.net/sonyjammie/sx4rv8ne/4/
You can try to use compose validator of RxwebValidators for using multiple validators. You can refer [https://stackblitz.com/edit/angular-48jrxb?file=src%2Fapp%2Falpha-numeric-add.component.ts] for your reference.
Typically you would validate this with either some validate() function on the submit button, or alternatively, if using the RXJS library, you can assign an [array of Validators] as a second #parameter to a FormControl object.
Also check out the official documentation on Form Validation from Angular.
In Angular6, you would keep the form's submit button disabled by using the [disabled] attribute on the button element, and assigning your specific conditions to said element's [disabled] attribute.
name:['',[Validators.required,Validators.minLength(3),Validators.maxLength(15),Validators.pattern('[A-Za-z]')]],

AngularJs - show validation message for custom form control

I have a custom form control (a directive which is not an input element) which implements ng-model (as suggested here) and it works fine. Validation is triggered on the form submit and the directive is made valid/invalid correctly.
The problem is how to display an error message. I tried like for normal form input fields:
ng-show="form.fieldName.$error.required"
but I cannot access field through name. form.fieldName is undefined.
Please make sure that you defined your form name inside of form tag. After that try to print formname.fieldname
Actually the problem was with transclusion. Once I fixed it element was normally accessible through the name.

Angular ng-model with required

I'm trying to create a simple input with html5 "required". I'm using placeholder, so I'd like the initial value of the input to be empty. I have the input bound to a ng-model that is initialized as empty (so the placeholder shows).
When I go to the page, it shows that input is required for the , which shouldn't show unless the user submits the form and the input is empty.
how can I do this:
<input type="text" required ng-model="name">
..in controller:
$scope.name = "";
and not have the form think I am submitting an empty input?
One way of only validating when the user has actually interacted with your input element is to use $dirty to determine wether to show your error message. e.g.
<span ng-show="form.name.$dirty && form.name.$error.required">
Name is required
</span>
I just created an example of form validation regarding to your question
This should be working:
http://plnkr.co/edit/6PTNg3atPHAjL0XFtvWj?p=preview

AngularJS multiple forms - how to submit forms by name?

I'm using Angular UI Bootstrap accordion with a form in each Accordion. How can I submit the form by the id or name of the form? In essence I have an click event bound to the accordion and I would like to pass the name of the form as a parameter somehow and then submit it?
thanks
http://plnkr.co/edit/GMJ8fTWqSw2STnG4V2Ri?p=preview
Instead of passing in the form's name or id, you should pass in the object that the form is bound to, or just dynamically pull it from the controller's $scope.
In angular it is considered bad form to have anything DOM related in your controller. By using the DOM in a controller it dramatically reduces the test-ability of the controller which is one of the key pillars that angular is built upon.
example:
<form ng-submit="handleSubmit(formData)">
<input ng-model="formData.field1"/>
<input ng-model="formData.field2"/>
</form>
Based upon your plnkr example to call the function defined in your form's rcSubmit attribute do this:
formElement.bind('submit', function () {
$parse(attributes.rcSubmit)();
});
The documentation for $parse states Converts Angular expression into a function which is exactly what you need in this case.

AngularJS, how do I make the UI dependent on which field has focus?

I have an AngularJS page with several form inputs.
When the some of the inputs have focus, I want to change other, arbitrary, aspects of the page.
For example, when the user is in the 'stock code' input, I want to display the list of popular stock codes. When they are in the 'qty' field I want to show in-stock quantities and lead times.
Is there a variable which contains the 'current' input (the one which has focus), or do I need to revert to jQuery's onFocus. (It seems a little primitive now.)
How about make a directive? You could set a variable whenever the user leaves/enters the input, and detect that: http://jsfiddle.net/TZnj2/
Be sure to read the directive guide if you're confused as to what's happening: http://docs.angularjs.org/guide/directive
Also I use scope.$apply in that directive, here's an explanation of what that does: http://docs.angularjs.org/api/ng.$rootScope.Scope#$apply
ngFocus and ngBlur are built-in directives:
<input ng-focus="hasFocus = true" ng-blur="hasFocus = false" type="text">
<p ng-show="hasFocus">The field has focus!!</p>
Try demo on jsfiddle

Categories

Resources