Reputation: 1438
I want to add custom validation to the angular form.
<div class="form-group" ng-class="{ 'has-error': contactform.inputAmount.$invalid && submitted }">
<label for="inputAmount" class="col-lg-2 control-label">Amount</label>
<div class="col-lg-10">
<textarea ng-model="formData.inputAmount" class="validate[required,custom[comment]] feedback-input" rows="4" id="comment" name="comment" placeholder="Enter Amount to Convert" required></textarea>
</div>
</div>
I want only number or decimal input with inverted commas like
"1"
"123.1"
"123.12221"
How can i add this pattern
Help would be highly appreciated.
Thanks
Upvotes: 0
Views: 2020
Reputation: 1426
You can use ng-pattern to validate your textarea.
Checkout here for example. http://www.java2s.com/Tutorials/AngularJS/AngularJS_Example/Directives/Use_ng_pattern_to_validate.htm
Refer here for dynamic ng-pattern validation Angularjs dynamic ng-pattern validation
Upvotes: 1
Reputation: 544
Use Directive for custom validations.
First write custom directive:
//Check For FLoat Validation
adminApp.directive('validateFloat', function() {
var FLOAT_REGEXP = /^\-?\d+((\.)\d+)?$/;
return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
// only apply the validator if ngModel is present and Angular has added the Float Number validator
ctrl.$validators.validateFloat = function(modelValue) {
return ctrl.$isEmpty(modelValue) || FLOAT_REGEXP.test(modelValue);
};
}
};
});
In directive used Regex for float (or) Decimal to check with ngModel value.
Then use directive in html page.
<input type="text" name="amount" class="form-control" ng-model=test.amount" validate-float required>
<span class="error-container" ng-show="myForm.amount.$dirty && myForm.amount.$invalid">
<span ng-cloak style="color:red" ng-show="myForm.amount.$error.required">Please Enter amount</span>
<span ng-cloak style="color:red" ng-show="!myForm.amount.$error.required&&myForm.amount.$error.validateFloat">Enter valid amount</span>
</span>
In HTML page mention the custom directive "validate-float" as attribute. And for showing error message in ng-Show mention the $error.validateFloat.
For more info about directive and validations: https://docs.angularjs.org/guide/directive, https://docs.angularjs.org/guide/forms
Upvotes: 0