Angular - Check if value entered into a field is a number - angularjs

In my Angular app I have a field that accepts either an email address or a phone number.
If a number is entered I want to show a particular span. However I can't seem to get this working.
So in my controller I have written:
$scope.isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Then in my HTML I have:
<form name="registrationForm">
<div>
Email or Mobile
<span ng-show="isNumber(registrationForm.usernameReg)">Include the country code.</span>
</div>
<input name="usernameReg" ng-change="main.change()" type="text" ng-model="main.username">
</form>
Any ideas why this wouldn't work?
Thanks.

You need to be testing the value of the model.
try
ng-show="isNumber(main.username)"
registrationForm.usernameReg is an object that contains numerous properties used as part of validation.
To better see this add <pre>{{registrationForm |json}}</pre> in your view

Related

Angularjs difference between fetched and locally modified data

I fetch data from an API and it gives my something like this:
{id: 1, name: ''}
The field name is ng-model for an input field.
As soon as I write something in the field, the json object I have a reference to, will have name equals to something else than empty.
That's normal behaviour.
However, if Im interested in knowing if name "was" empty when I fetched data, can I do this in a simple way? Without needing to create new variables?
Basically I want to have 2 ng-if elements and only display one of them. But I cannot trust the data in the object because I don't know if the name-field has been changed locally or on the server:
<input type="text" ng-model="ctrl.name" ng-if="ctrl.name === ''" />
<span ng-if="ctrl.name !== ''">{{ctrl.name}}</span>
Use can the $dirty (this docs are about form but it's true for inputs as well) prop of an input in form so the logic will be: show the input if the name is not defined (undefined or an empty string) or when the input is dirty - means the user typed in the input. And the opposite for the span. This way you'll not have to hold another param.
angular.module('app', []).controller('myController', function() {
// comment this line to simulate name was empty
// this.name = 'text from server';
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myController as ctrl">
<form name="myForm">
<input type="text" name="name" ng-model="ctrl.name"
ng-if="!ctrl.name || myForm.name.$dirty" />
<span ng-if="!!ctrl.name && !myForm.name.$dirty">{{ctrl.name}}</span>
</form>
</div>
</div>

Deletion Error with Email Validation in Angular

So I've recently taken over an Angular Giving Form Application. I am running validation on the email field using ng-pattern and displaying the errors on blur with ngMessages. The validation works great, however once the validation passes as $valid if the user decides they need to make a change in their email and begin to delete part of the first deletion deletes the last character of the email as expected, but the second deletion deletes the entire field forcing the user to start from scratch.
The regex for ng-pattern is being set in the controller scope with the variable $scope.emailre
The files are much to large to place here but here is the link to the site I am working on for my client.
https://epiqa.moodyglobal.org/corporate/
Snippet of Angular controller:
myApp.controller('mainCtrl', function($scope, localStorageService, $http) {
$scope.emailre = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
Snippet of HTML Form:
<div class="row form-group">
<div class="col-sm-6">
<div>
<label class="label" for="txt_donorEmail">E-mail:</label>
<input ng-class="{ 'submitted-error' : givingForm.email.$invalid && submitted }" ng-model="email" type="text" id="email" name="email" class="textbox required full form-control" maxlength="50" ng-pattern="emailre" required />
</div>
<div ng-messages="givingForm.email.$error" ng-if="givingForm.email.$touched || submitted">
<div class="errorText" ng-message="required">This field is required</div>
<div class="errorText" ng-message="pattern">Enter a valid email</div>
</div>
</div>
</div>
I have tried changing the input type from type="text" to type="email" but when doing that any time the user types two (.) periods the field gets immediately deleted.
Please help any ideas are very welcome.
The behavior is caused by this section
$scope.$watch('email', function(value){
localStorageService.set('email',value);
$scope.emailValue = localStorageService.get('email');
});
By Angular documentation
The default behaviour in ngModel is that the model value is set to undefined when the validation determines that the value is invalid. By setting the allowInvalid property to true, the model will still be updated even if the value is invalid.
I'm not sure whether you want to save the invalid email into localStorage, though. Maybe you can add a check only update when the value is valid.

Show ? in textbox when textbox have ng-pattern for numeric validation

I need to show '?' when the value not able to read from scanner which returns me value by including '?'
Let say document has sr no as '123' but let say for some reason scanner not able to read it then it returns me as "12?" or "???" or "?23" or "1?3"
If any digit which is not readable that need to corrected by user manually for that i need to show them in to the textbox.
In our application we are using angularjs validations, which are not allowing me to show above values inside textbox as it contains '?' which is not numeric value.
Also I should enforce the numeric validation so that user can correct the above and submit to the server.
So how we achieve this functionality ?
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="text" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<input ng-show="toggle" type="submit" value="submit"/>
<input ng-show="!toggle" type="button" ng-click="AfterProcessing()" value="After Processing"/>
<input type="button" value="Reset" ng-click="reset()"/>
<br/>
<span>Activity : {{message}}</span>
</form>
</div>
JS code
function formCtrl($scope){
$scope.price= "123";
$scope.toggle = false;
$scope.message="No Activity";
$scope.onSubmit = function(){
$scope.toggle=false;
$scope.message="onSubmit clicked...";
}
$scope.AfterProcessing = function(){
$scope.toggle=true;
$scope.price ="1?3";
$scope.message="AfterProcessing clicked...";
}
$scope.reset=function()
{
$scope.toggle=false;
$scope.price ="123";
$scope.message="Reset clicked...";
}
}
I have created sample as below.
Plz check on JsFiddle sample
-Thanks
You need to create a CSS Class that will be applied to text box. Using :before and :after pseudo css construct, you can add ? character and get desired result.
So,
1. Define a CSS Class with :before and/or :after as per your requirement
2. On the HTML, use ng-class="{'your-class': $error, 'regular-class': '$pristine'}"
Let me know if you need a code sample and a plunker. (I am at the end of the day. May be will provide some code tomorrow. )
If you can create a plnkr based on above and submit link here, more people would be able to help you. thanks.

AngularJS post form to external URL

I have the following form in my AngularJS app which contain hidden fields with values filled based on user selection on some inputs on the form (radio buttons...etc), when the user click on the Submit link I should route the user to an external URL while passing hidden fields just as any normal form submission. Unfortunately I can't do this as some of the hidden field values are dependent on some calculations inside a function of the view related controller (as shown below in controller code, so I was wondering is there a way I can call the controller function from this form, then the controller function post the whole form and its field? Any example is highly appreciated. Thanks.
Note I am using link instead of a button.
<form name="clientPaymentForm" id="clientPaymentForm" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">>
<div>
<fieldset>
<input id="name" type="text" required placeholder="Client Name" ng-model="client.name">
...
...
<input type="hidden" name="amount" ng-value="order.total">
...
...
<a class="orderButton" href="javascript:{}" onclick="document.getElementById('clientPaymentForm').submit(); return false;">Order Now</a>
</fieldset>
</div>
</form>
Controller:
$scope.processOrder = function(){
//Order calculation happens here to update order.total value and can only happen after click click Order Now to place the order...
};
I guess this is a bit late, but what you want to use is the ng-click directive which will allow you to call functions defined directly on the scope.
Assuming that you've defined $scope.processOrder, change your a tag to the following:
<a class="orderButton" ng-click="processOrder()">Order Now</a>
And everything should work as hoped.
Alternatively, you could use ng-submit on the form to have it work when you press the "Enter" or "Return" key, as in:
<form name="clientPaymentForm" id="clientPaymentForm" action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" ng-click="processOrder()">.

How to show 'invalid date' validation message for AngularStrap datetimepicker

I am able to validate my AngularStrap datetimepicker, but I cannot differentiate between a required validation failure and an invalid date failure. The only error that ever shows on screen is the required error, whether it is required or an invalid string. Is it possible in cases where a string has been entered that is invalid to show a different validation message? Here is my code :
<div class="control-group" ng-class="{error: form.BirthDate.$invalid}">
<label class="control-label" for="BirthDate">{{'_BirthDate_' | i18n}}</label>
<div class="controls">
<input id="BirthDate" name="BirthDate" title="BirthDate" type="text" ng-model="user.BirthDate" data-date-format="dd/mm/yyyy" bs-datepicker required>
<span ng-show="form.BirthDate.$dirty && form.BirthDate.$error.required">{{'_BirthDateRequired_' | i18n}}</span>
<!--<span ng-show="form.BirthDate.$dirty && form.BirthDate.$error.pattern">{{'_BirthDateInvalid_' | i18n}}</span>-->
</div>
</div>
What I want is something similar to the ng-pattern check but specific to the datetimepicker.
first of all, I think this has no real link with the date picker or not, if I understand your problem, you are trying to display different messages according to the error that lead to the $invalid for the form
If it's the case, the code you provided will only show a message when the date is invalid (but only because you commented the part for the pattern ;) )
I was super lazy while testing, so I didn't use the datepicker, you'll have to enter a date manually, but I did this fiddle : http://jsfiddle.net/DotDotDot/ELf5A/2/
As I didn't know exactly in what context you were using it, I used different methods to display validation error messages
The HTML part is simple. There is a form, two fields required, one with a pattern check for the date, the other only for the required validation. I added 2 error messages for the date, one displayed when the form hasn't been touched, telling you what format is expected, the other only shows up when the pattern is wrong.
You can click on the button to check the whole validation and then show another message, which will tell you if the form is valid or not, and if not, if it's because of the pattern of the date.
<div ng-controller='theCtrl'>
<form name='theForm'>
Enter something here : <input type='text' ng-model='someField' name='someField' required /> <br/>
Enter a date here : <input type='text' ng-model='theDate' name='theDate' ng-pattern='datePattern' required />
<span ng-show='theForm.theDate.$error.pattern'>Your date format is invalid, please check it again</span>
<span ng-show='theForm.theDate.$pristine'>Enter a valid date here : DD/MM/YYYY</span>
<br/> <input type='button' ng-click='validation(theForm)' value='Try to validate me!' />
<br /> {{errorMsg}}
</form>
</div>
The JS part is not very complicated either. When you click on the button, the form is being sent to the validation function, which will actually do all the checks you want, I only did the one corresponding to the pattern, but you could totally check whatever you want about the validation
$scope.validation=function(aForm){
//console.log(aForm)
if(aForm.theDate.$error.pattern)
$scope.errorMsg='The pattern you entered isn\'t good enough, try again !'
else{
if(aForm.$invalid)
$scope.errorMsg='Something is invalid, please check all the fields !'
else//valid
{
$scope.errorMsg='Not bad !'
alert("good job !")
//maybe you can also submit this form here ;)
}
}
}
This validation function could totally be used as the trigger in a ng-show/ng-hide too, this is why I also added another function :
$scope.whatToDisplay=function(aForm){
if(aForm.$valid)
return 'valid';
if(aForm.theDate.$error.pattern)
return 'date';
if (aForm.$invalid)
return 'notdate';
}
This will return a string corresponding to what is happening during the validation, which will be handled with ng-show :
<span ng-show='whatToDisplay(theForm)=="date"'>Displayed if the date is wrong</span>
<span ng-show='whatToDisplay(theForm)=="notdate"'>This is displayed if the form is invalid, but not because of the date format</span>
<span ng-show='whatToDisplay(theForm)=="valid"'>Displayed if the form is valid</span>
To summarize a bit, you can use 4 different methods
A validation function triggered with a click (useful for submit buttons), corresponding to the validation() function in my fiddle
A function associated with some ng-show, which will automatically watch every change, like the whatToDisplay() function
The ng-show associated with only the form attributes, like what you were doing with your code
The class automatically applied to the form ( I didn't explain it, but you can see it in the fiddle, the border change if the pattern is wrong or if it's only invalid )
Sorry, I had some difficulties to make this short, I let you play with the code, it's easier to understand that way, I hope this will help you
You should use ngMessages in AngularJS 1.3 to do the error messaging with less code and complexity. The bs-angular directive creates a message for the "date" string value of ng-message in your list of messages.
<div class="control-group" ng-class="{error: form.BirthDate.$invalid}">
<label class="control-label" for="BirthDate">
{{'_BirthDate_' | i18n}}
</label>
<div class="controls">
<input id="BirthDate" name="BirthDate" title="BirthDate" type="text"
ng-model="user.BirthDate" data-date-format="dd/mm/yyyy"
bs-datepicker required>
<span ng-show="form.BirthDate.$dirty && form.BirthDate.$error.required">{{'_BirthDateRequired_' | i18n}}</span>
</div>
<div class='alert alert-danger' ng-messages='myForm.BirthDate.$error'
ng-if='!myForm.BirthDate.$valid'>
<div ng-message="date">Please enter a valid date</div>
<div ng-message="required">Birthdate is required</div>
</div>
</div>
This code helps to show the invalid datetime error message
$scope.date=='Invalid Date'
{
err('Your error message');
}

Resources