angularjs ng-minlength validation is not working, form still being submitted - angularjs

I am trying to submit the form on only successful validation.
validation is working for required but not working for ng-minlength
form input is invalid but form is still being submitted.
<form name="myForm" ng-submit="count = count + 1" ng-init="count=0" ng-app>
<div class="control-group" ng-class="{error: myForm.mobile.$invalid}">
<label class="control-label" for="mobile">Mobile</label>
<div class="controls">
<input type="text" name="mobile" placeholder="07XXXXXXXXX" ng-model="mobile" ng-minlength="11" required />
<span ng-show="myForm.mobile.$error.required" class="help-inline">Required</span>
<span ng-show="myForm.mobile.$error.minlength" class="help-inline">Mobile number should be minimum 11 character starting from 07</span>
</div>
</div>
<div class="control-group">
<div class="controls">
<input class="btn" type="submit" value ="submit" />
</div>
count: {{count}}<br />
<tt>myForm.$invalid = {{myForm.$invalid}}</tt><br/>
</div>
</form>
http://jsfiddle.net/pMMke/9/
what am I doing wrong.
I don't want to use submit button disable method.

This is what you are doing wrong: you are mixing two concepts, Angular validators and
HTML5 validators.
The required HTML5 validators, for instance, states that:
When present, it specifies that an input field must be filled out before submitting the form.
So, if you try to submit a form that has an input with this attribute, it will show a message explaining this to the user, and it will prevent the form from being sent. This is the behavior you want. Why isn't working for ng-minlength? Because ng-minlength is an Angular validator (you can tell because it begins with ng-), and it doesn't add any special behavior to the form. It simply set the input where it is located to invalid (and hence, the form), and let you decide what to do with it.
You have an option: you can use the pattern HTML5 validator, to specify the field requires at least 11 characters. It would like this:
<input type="text" pattern=".{11,}">
So when you submit a form containing this input, it will no be sent if the user has enter less than 11 characters.
But since we are it, and you are already using the pattern validator, you could use the regular expression in its full potential, and define something like:
<input type="text" pattern="07[0-9]{9}" />
Which will only admit values of 11 characters, that start by "07" and that contains only digits. I have modified your fiddle to show you how it would work: http://jsfiddle.net/helara/w35SQ/

I mistakenly used ngMaxlength="12" ngMinlength="6" instead of ng-minlength="6" ng-maxlength="12", it's working fine now.

Both ng-minlength & mg-maxlength works in AngularJS.
I've tested this in AngularJS version 1.3.
Make sure to use novalidate with <form> to disable browser's native validation.

This should work:
To enter mobile number
ng-show="myForm.mobile.$touched && myForm.mobile.$error.required"
For minimum length
ng-show="myForm.mobile.$touched && myForm.mobile.$error.minlength"
For maximum length
ng-show="myForm.mobile.$touched && myForm.mobile.$error.maxlength"

This work for me guys
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input ng-minlength="11" class="mdl-textfield__input" type="text" name="cpf" id="cpf" ng-model="avaliacao.cpf" ng-required="true" ng-pattern="/^\d+$/">
<label class="mdl-textfield__label" for="cpf">CPF *</label>
</div>
<p style="color: #d50000;" ng-show="myForm.cpf.$error.required && myForm.cpf.$dirty">Field Required</p>
<p style="color: #d50000;" ng-show="myForm.cpf.$error.pattern">Only numbers</p>
<p style="color: #d50000;" ng-show="myForm.cpf.$error.minlength">Min 11 Chars</p>

I'm facing the same issue, and I think you can only disable the button or ignore the entered value by yourself. You can also check the $valid property in your controller and ignore the value... It is not so nice, but I found no other way.

Related

Is it possible to use form attribute in angularjs for form validation?

Please think in angularjs way.
Actually my layout is different.
I have input fields inside form and also have input fields outside form, this is a special case in my product.
I know about form attribute in HTML5
But
In AngualrJS:
I want to achieve outside form input fields works as good as inside form input field works for validation purpose.
Is it possible? We can not remove the place of form tag.
If Yes please guide me.
<div ng-app="myApp" ng-controller="validateCtrl" >
<h6>Validation Example</h6>
<form id="frm" name="myForm" novalidate>
Inside form
<p>
<input type="submit" ng-disabled="myForm.email.$dirty && myForm.email.$invalid">
</p>
</form>
Outside form
<p>Email:<br>
<input form="frm" type="email" name="email" ng-model="email" required>
</p>
</div>
Plunker

Angular: Elegant way to toggle visibility of two related inputs

I have 2 related inputs in angular one is type number and the other is type text.
They both display the same value with the only difference being that the type text input displays the value of the type number input formatted for currency.
Only one of these is displayed at any given time. The behaviour I'd like is for the text input to be displayed initially and then on the click event the text input is hidden and the number input is shown. Similarly when the blur event happens on the number input the number input is hidden and the text input is shown.
The markup for this looks something like this:
<div>
<input type="number" ng-model="aValue" ng-blur="hideMeAndShowInputBelow">
<input type="text" ng-value="aValue | currency:'': '0'" ng-click="hideMeAndShowAndFocusInputAbove" readonly="readonly">
</div>
I know I could add extra properties to make this work but being relatively new to Angular this feels like the sort of thing that there is probably an elegant solution for.
Any help would be much appreciated.
You can assign a variable in ng-blur/ng-click and hide/show the inputs depending on the variable value.
<div>
<input type="number" ng-model="aValue" ng-show="showNumber" ng-blur="showNumber = false">
<input type="text" ng-value="aValue | currency:'': '0'" ng-show="!showNumber" ng-click="showNumber = true" readonly="readonly">
</div>
Check the plunker here:
https://plnkr.co/edit/yMFiXWuUF1R9BPGr2usT?p=preview
Alternatively, if this is a component you're going to use multiple times around your app, you could create a custom directive that achieves the same functionality, and thus avoid a lot of code duplication etc.
Try out something like this
<div ng-app="myApp" ng-controller="myCtrl">
<button class="btn btn-success" type="text" ng-model="firstName" ng-show="display" ng-click="display=!display"> BUTTON 1</button>
<br />
<button class="btn btn-warning" ng-click="display=!display" ng-model="lastName" ng-show="!display"> BUTTON 2
</button>
</div>
DEMO
Thanks for the suggestions. I followed the same approach but because I had some additional requirements (I wanted the value to be focussed when switching to the edit mode so the user can edit immediately without having to click the input again) I ended up writing a directive. It's here:
PLUNKER
But here is the markup.
<div class="mt-flight-input" ng-class="{'mt-dirty': value.newvalue != value.initial, 'mt-zero': value.newvalue == 0}">
<input type="number" class="mt-input" placeholder="0" ng-show="value.isAuthoring" ng-model="value.newvalue" ng-blur="checkValue('blur', value)" ng-focus="checkValue('focus', value)">
<input type="text" class="mt-input" placeholder="0" ng-show="!value.isAuthoring" ng-value="value.newvalue | currency:'': '0'| comma2dots" ng-click="showEditor($event, value)" ng-focus="showEditor($event, value)" readonly="readonly">
</div>

angularjs: ng-message always showing

I'm using angular-messages to display form validation errors on my angular app.
As per the documentation, I have built the following code
<form name="loginForm">
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="data.email" name="email" required>
</label>
<div ng-messages="loginForm.email.$error" style="color:maroon">
<div ng-message="required">Please input a valid e-mail address</div>
<div ng-message="email">You did not enter your email address correctly...</div>
</div>
</form>
I have included the ngMessages directive in my javascript as well as imported the angular-messages.js file.
Unfortunately, these two messages are showing perpetually. Regardless of what I type in the input field, be it a valid email or not. Both messages are always showing. If I try to only include one ng-message, the result is the same.
What could I be doing wrong?
edit: In case my description isn't very clear, this is a print of the result
https://s9.postimg.cc/du9230tdb/Screen_Shot_2015_06_26_at_17_09_24.png
You gotta make sure you are actually including ngMessage to your module.
var app = angular.module('app', [
'ngMessages'
])
... and that you included the library to your project
<script src="/scripts/vendors/angular-messages/angular-messages.js"></script>
Everything seems to be fine in the code you're sharing.
<form name="loginForm">
<label class="item item-input">
<input type="email" placeholder="Email" ng-model="data.email" name="email" required>
</label>
<div ng-messages="loginForm.email.$error" style="color:maroon">
<div ng-message="required">Please input a valid e-mail address</div>
<div ng-message="email">You did not enter your email address correctly...</div>
</div>
</form>
Here is a working copy on Plunker I'm using your piece of code.
From Angularjs documentation.
By default, ngMessages will only display one error at a time. However, if you wish to display all messages then the ng-messages-multiple attribute flag can be used on the element containing the ngMessages directive to make this happen.
If you want to show the errors after the field is dirty, please visit this link.
Make sure you are including ngMessage module and the library as well. Please see Carlos's answer.
Thanks
Check with
<div ng-messages="loginForm.email.$error" ng-show="loginForm.email.$invalid && loginForm.email.$touched">
...
</div>
This trick saved my day.

Angular form that contains nested directive not validating

I have a very simplified bit of html like so:
<call-panel>
<form name="hotListForm" >
<twilio>
<input type="text" name="phoneOtherText" id="phoneOtherText" class="form-control" required="required" ng-model="phoneNumber" ng-pattern="validation" ng-trim="false"/>
<span class="error" ng-show="hotListForm.phoneOtherText.$error.pattern">Not a valid phone number</span>
</twilio>
</form>
</call-panel>
But this doesn't work. Is there a special way to do this when in a nested directive. I have verified pattern is available.
Screenshot of it definitely being in the form and of form structure:
It is not working probably because you have the id set to "phoneOtherText" as well, try changing the id and try

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