Bit of a trivial one here however am new to Angular so excuse me.
Whenever I have an input field - I only want an action to occur if the field actually contains some valid content.
What i find I'm having to do is first instantiate a variable, then assign that to whatever input there is then do a boolean check in a if.
Is the the correct way to go around this? If i don't instantiate the variable (or don't use one at all) i run into getting undefined error:
var textToSearch = '';
textToSearch = $scope.main.searchInputField.trim();
if (textToSearch){
$location.path('/search/'+textToSearch);
}
Also (on another note)
I'm sanitising everything on the server side however on Angular/client side is there a quick and easy function I can use?
Thanks
I suppose you have an ng-model for 'main.searchInputField' so if you want to check if the field is empty you can just write
$scope.main = {};
if($scope.main.searchInputField.trim().length > 0){
//do stuff
}
suppose you have ng-model of input field 1 as some.data and input field 2 as some.data1
for(var i=0; i<$scope.some.length;i++){
if($scope.some[i]){
//do something
}
}
it will check every field.
This is using Bootstrap for email validation, but the same logic applies if you are using your own classes.
<div ng-class="(emailRegExp.test(email) && email != null) ? 'has-success' : 'has-error'" class="form-group has-feedback">
<div class="input-group">
<div class="input-group-addon">
<span class="glyphicon glyphicon-envelope"></span>
</div>
<input ng-model="email" ng-change="checkEnableSubmit()" id="email" placeholder="Email Address" type="text" class="form-control" aria-describedby="emailStatus">
</div>
<span ng-class="(emailRegExp.test(email) && email != null) ? 'glyphicon-ok' : 'glyphicon-remove'" class="glyphicon form-control-feedback" aria-hidden="true"></span>
</div>
The ng-class directive accomplishes the validation if:
The checkEnableSubmit() function in your controller only allows a submission when the data is valid (I would be happy to include that code, too)
Both classes in the ternary operator on line #1 indicate valid data and non-valid data (in this example one makes the input appear green and the other red)
Related
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.
I'm looking for a way to use a single parsley validation error message for a set of input fields. The primary example of this would be for an address input field, but I'm sure others can come up with similar examples where this might be useful.
<div id="error-container"></div>
<input name='address1' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
<input name='address2' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
<input name='address3' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
Using the above code right now would result in 3 different error messages, but I want to set up a scenario where only one message would be displayed if any of the inputs are invalid.
Thanks in advance
Update
After a bit of JS console fun, I think I've found something that works. The idea below is to prevent any UI changes being done by parsley on the group, and to trigger a check on the whole group each time one of the elements are validated. This may not be the best way to do things, but it appears to be working with my single test-case. I'm thinking that this could be re-worked into a validator so that I can re-use it for other sets of inputs in the future.
<div id="error-container"></div>
<input name='address1' data-parsley-ui-enabled='false' data-parsley-trigger='change' data-parsley-group='address-grp' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
<input name='address2' data-parsley-ui-enabled='false' data-parsley-trigger='change' data-parsley-group='address-grp' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
<input name='address3' data-parsley-ui-enabled='false' data-parsley-trigger='change' data-parsley-group='address-grp' data-parsley-maxlength="255" data-parsley-errors-container="#error-container">
var $addressFields = $("[data-parsley-group='address-grp']");
addressFields.each(function(index, element) {
$(element).parsley().on('field:validated', function(parsleyField) {
var fieldOptions = parsleyField.actualizeOptions().options;
var classHandler = fieldOptions.classHandler(parsleyField);
var container = $(fieldOptions.errorsContainer);
classHandler.removeClass(fieldOptions.successClass);
classHandler.removeClass(fieldOptions.errorClass);
var valid = parsleyField.parent.isValid(fieldOptions.group);
if(valid) {
console.log("Valid");
classHandler.addClass(fieldOptions.successClass);
container.html("");
} else {
console.log("Invalid");
classHandler.addClass(fieldOptions.errorClass);
container.html("Error");
}
});
});
You can do this fairly cleverly with a bit of CSS if you add a particular class to your error container.
HTML:
<div id="error-container" class="parsely-single-error"></div>
CSS:
.parsely-single-error .filled ~ .filled {
display: none;
}
Explanation
The CSS reads, "hides any child elements of the error-container that have the class 'filled' and come after another element that has the class 'filled'". This has the effect of hiding all but the first 'filled' error in the error container.
For reference, the parsely error container looks like this when filled:
<div class="parsely-single-error" id="error_container">
<span class="help-block filled" id="parsley-id-5">
<div class="parsley-required">This value is required.</div>
</span>
<span class="help-block" id="parsley-id-7"></span>
<span class="help-block filled" id="parsley-id-9">
<div class="parsley-required">This value is required.</div>
</span>
<span class="help-block filled" id="parsley-id-11">
<div class="parsley-required">This value is required.</div>
</span>
<span class="help-block" id="parsley-id-13"></span>
</div>
I'm not sure there a great way to do this.
You could try configuring it so that errors are put in the same container, and then use CSS to only show the :first of them?
I have a directive which is used for text field and the directive has a validation like below which should show a message when the textfield length is less than 5 characters.
attrs.$observe('useNumberRegex', function( val ) {
scope.useNumberRegex = GenericFieldUtils.castBoolean(val, false);
if(scope.useNumberRegex)
{
scope.regExp = /^\d+$/;
}
});
and the directive template URL points to html as shown below
<li ng-if="editable && (cssClass == 'text_style_filter' || cssClass == 'drp_down_style')" style="float:left;width:42%" class="{{$parent.cssClass}}">
<input id="{{$parent.uniqueId}}" name="{{$parent.name}}" type="{{$parent.textType}}" class="field-control {{$parent.numCssClass}}" ng-pattern="$parent.regExp" autocomplete="off" ng-required="mandatory" ng-maxlength="{{maxLength}}" maxlength="{{maxLength}}" ng-model="$parent.value" ng-disabled="disabled" ng-blur="$parent.onBlur($parent.value)" ng-keyup="$parent.onKeyup($parent.value)" aria-label="{{$parent.ariaLabelInput}}" min="{{min}}" max="{{max}}" validate>
<div ng-if="$parent.formController.submitController.attempted">
{{$parent.regExp}}
<span class="error-message" ng-repeat="error in errors" translate>{{error}}fdsfsdfsdf</span>
</div>
</li>
Can you please help me what is going wrong in displaying a message when the length is less than 5 characters long.
You can use ng-minlength to actually validate the length of the input.
You could also use the regex pattern to validate the same. Instead of /^\d+$/ use /^\d{5,}$/
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.
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');
}