Angular validation for fields to be valid but not required - regex

I have the following in my template:
<div class="form-group">
<label for="work_phone">Work Phone</label>
<input type="text"
class="form-control"
name="workPhone"
ng-class="{'borderRed': contactInformation.workPhone.$invalid && contactInformation.submitted}"
ng-model="controller.contactInformation.workPhone"
ng-pattern="/^\d+$/"
maxlength="10"
id="work_phone">
<small class="error"
ng-show="contactInformation.workPhone.$invalid && !contactInformation.workPhone.$pristine && contactInformation.submitted">
That's not a valid phone number (only numerics are allowed)!
</small>
</div>
Conditions:
1. If the field is blank/untouched, the form should stay valid.
2. If there is any value in the field then it should be validated against the regex provided in ng-pattern.
Looks very trivial. I know. But for some stupid reason, unable to find a solution

So if i understand your problem you want allow only numerics you can use this directive to block every other caracters :
.directive('onlyDigits', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9]/g, '');
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits,10);
}
return undefined;
}
ctrl.$parsers.push(inputValue);
}
};
});
And add the directive to your input, it's faster and you haven't to use ng-pattern :
<input type="text"
class="form-control"
name="workPhone"
maxlength="10"
id="work_phone" onlyDigits>

Your form currently stays valid to begin, because you're checking for $pristine. Try using $setPristine() when the form is empty to reset it, so no longer gets the error class.

You may change your regex so that it allows empty strings:
ng-pattern="/^\d*$/"

Related

How to use the Regular Express of the end pattern in the next pattern not the entire string?

I am trying to find the categories in a website by using Regular Expression.
I typed (?<=class="category-section" data-id=")(.*)(?=" id="nav)
but it return the whole string to me, and what I see it start from the first pattern after data-id=" until the end pattern has " id="nav
For Example:
<div class="category-section" data-id="Motors" id="nav-1">
<div class="category-section" data-id="Fashion" id="nav-2">
I expected to get Motors and Fashion in the matches but it wil return
Motors" id="nav-1"> <div class="category-section" data-id="Fashion
I dont get it....
Try this:
data-id=".*?"
It will return two matches, then correspond to data-id="Motors" and data-id="Fashion".
So, you can replace the data-id= and " sings to get your desire value, inside attributes.
Edit 1:
By using simple js functions, you can retrieve this value:
<div class="category-section" data-id="Motors" id="nav-1">Content1</div>
<div class="category-section" data-id="Fashion" id="nav-2">Content2</div>
<script>
(function() {
var data = document.getElementsByClassName('category-section');
for (var i = 0; i < data.length; i++) {
console.log(data.item(i).getAttribute('data-id'));
}
})();
</script>
Output:
Motors
Fashion

angular2 - adding 'pattern' for form builder

I have a pattern for a form builder and I have this:
this.userForm = this.formBuilder.group({
'postalCode': ['', Validators.pattern('/[A-Za-z][0-9][A-Za-z] [0-9][A-Za-z][0-9]/i')]
});
I have a ValidationService which I've added a function "getValidatorErrorMessage".
static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
let config = {
'pattern': 'invalid pattern'
};
return config[validatorName];
}
My template has:
<div>
<label for="postalCode">Postal code (A1A 2J3)</label>
<input formControlName="postalCode" id="postalCode" />
<control-messages [control]="userForm.controls.postalCode"></control-messages>
</div>
But for some odd reason, the validation messages arent displaying if I dont follow the regex code.
You can view the plunkr here.
That's because you set a condition in your ControlMessagesComponent that input field has to be touched in order for error message to be displayed:
get errorMessage() {
for (let propertyName in this.control.errors) {
if (this.control.errors.hasOwnProperty(propertyName) &&
this.control.touched) { // this line
return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
}
}
return null;
}
If you remove this.control.touched, validation will be performed as you type. But this also will result in required messages being displayed right away. Combination I prefer most is to display error message in two cases: when user clicks on input field and then clicks somewhere else or when user starts typing which can be achieved with following condition:
if (this.control.errors.hasOwnProperty(propertyName) &&
this.control.dirty ||
this.control.touched)

How do I correctly wrap a TEXT and hand it to my Template Mark ###SEARCH_FIELD###

I am currently getting back into typo3 and I have really big problems with the variable concept, it just doesn't do what it is supposed to. See the first Mark SCROLLUP, everything works fine there, but I don't know to get it working for a more complex part.
page.10.marks {
SCROLLUP = TEXT
SCROLLUP.value = <div id="scrollup_button"> </div>
temp.suche = TEXT
temp.suche {
<input type="hidden" name="tx_indexedsearch[sections]" value="0" />
<input name="tx_indexedsearch[submit_button]" value="Search" type="hidden" />
<input name="search" src="images/search_red.png" value="Search" class="searchbox-button" type="image" />
}
temp.suche.wrap = <form action="suchergebnisse/" method="post" id="indexedsearch">|</form>
SEARCH_FIELD < temp.suche
}
There are three problems:
You need to set the value of a TEXT object under its value property (cf. TypoScript reference):
temp.suche = TEXT
temp.suche.value = [...]
or
temp.suche = TEXT
temp.suche {
value = [...]
}
Multiline values have to be placed in parenthesis, not braces:
temp.suche.value (
line 1
line 2
...
)
The object temp.suche should be placed at top level, outside the page.10.marks object:
temp.suche = TEXT
temp.suche.value = [...]
page.10.marks {
SEARCH_FIELD < temp.suche
}

How do you know when templates have been initialized in polymer dart?

The polymer js docs say you have to listen for the WebComponentsReady event to know when the polymer elements have been set up. What's the equivalent in Dart?
Here's my template:
<template id="order_name" bind repeat>
<div class="accordion-group">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#order_list" href="#collapseOne">
{{commonName}} ({{scientificName}})
</a>
</div>
<div id="collapseOne" class="accordion-body collapse">
<div class="accordion-inner">
...
</div>
</div>
</div>
</template>
And here's main:
void main() {
OrderList().then((order_data) {
query("#order_name").model = order_data;
print (queryAll(".accordion-heading")); //null
}).catchError((err) => print(err));
query("#my-button").onClick.listen((Event e) {
print (queryAll(".accordion-heading")); //[div,div]
});
}
OrderList is a wrapper around HttpRequest.getString() and returns a future. My thought was to use an event like WebComponenentsReady to know when the template had been fully instantiated. The base question is how can I get at the .accordion-heading divs in main so I can attach listeners to them?
I assume that you are using boot.js. if you are, they should be initialized by the time you program enters main().
According to the spec (https://www.dartlang.org/articles/web-ui/spec.html#main-script):
...you cannot query for children of conditional and iteration nodes. ...To retrieve a component instance you need to defer queries until the end of the event loop, for example using a Timer.run(f).
So the code above needs to be modified like this:
void main() {
OrderList().then((order_data) {
query("#order_name").model = order_data;
print (queryAll(".accordion-heading")); //null
Timer.run( () => print (queryAll(".accordion-heading"))); //[div,div]
}).catchError((err) => print(err));
query("#my-button").onClick.listen((Event e) {
print (queryAll(".accordion-heading")); //[div,div]
});
}

angularjs if statements?

So I'm running through the tutorial for AngularJS:
I have an array defined in the controller and i'm returning different points in the array by calling when i'm looping through ng-repeat {{feature.name}} {{feature.description}}
What i don't understand is lets say i have a third point in the array called "importance" and it's a number from 1 to 10. I don't want to display that number in the html but what i do want to do is apply a different color to the feature if that "importance" number in the array is 10 vs 1
so how do i write an if statement to do this:
i.e.
<p style="**insert if statement: {{if feature.importance == 10}} color:red; {{/if}} **">{{feature.description}}</p>
no idea if that's right but that's what i want to do
I do not think there is if statement available.
For your styling purpose, ng-class can be used.
<p ng-class="{important: feature.importance == 10 }">
ng-switch is also convenient.
-- update --
take a look at:
https://stackoverflow.com/a/18021855/1238847
angular1.2.0RC seems to have ng-if support.
Actually there is a ternary operator in Angular 1.2.0.
<p style="{{feature.importance == 10 ? 'color:red' : ''}}">{{feature.description}}</p>
I think the answer needs an update.
Previously you could use ngIf directive from AngularUI project (code here if you still want to download it), bad news is that it's not maintained any more.
The good news is that it has been added to the official AngularJS repo (unstable branch) and soon will be available in the stable one.
<div ng-if="something"> Foo bar </div>
Will not just hide the DIV element, but remove it from DOM as well (when something is falsy).
ng-class is probably the best answer to your issue, but AngularUI has an "if" directive:
http://angular-ui.github.com/
search for:
Remove elements from the DOM completely instead of just hiding it.
I used "ui-if" to decide if I should render a data value as a label or an input, relative to the current month:
<tbody id="allocationTableBody">
<tr ng-repeat="a in data.allocations">
<td>{{a.monthAbrv}}</td>
<td ui-if="$index < currentMonth">{{a.amounts[0]}}</td>
</tr>
</tbody>
In the case where your priority would be a label, you could create a switch filter to use inside of ng-class as shown in a previous SO answer : https://stackoverflow.com/a/8309832/1036025 (for the switch filter code)
<p ng-class="feature.importance|switch:{'Urgent':'red', 'Warning': 'orange', 'Normal': 'green'}">...</p>
You can also try this line of code below
<div class="{{is_foo && foo.bar}}">
which shows foo.bar if is_foo is true.
This first one is a directive that evaluates whether something should be in the DOM only once and adds no watch listeners to the page:
angular.module('setIf',[]).directive('setIf',function () {
return {
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'A',
compile: function (element, attr, linker) {
return function (scope, iterStartElement, attr) {
if(attr.waitFor) {
var wait = scope.$watch(attr.waitFor,function(nv,ov){
if(nv) {
build();
wait();
}
});
} else {
build();
}
function build() {
iterStartElement[0].doNotMove = true;
var expression = attr.setIf;
var value = scope.$eval(expression);
if (value) {
linker(scope, function (clone) {
iterStartElement.after(clone);
clone.removeAttr('set-if');
clone.removeAttr('wait-for');
});
}
}
};
}
};
});
This second one is a directive that conditionally applies attributes to elements only once without watch listeners:
i.e.
<div set-attr="{ data-id : post.id, data-name : { value : post.name, condition : post.name != 'FOO' } }"></div>
angular.module('setAttr',[]).directive('setAttr', function() {
return {
restrict: 'A',
priority: 100,
link: function(scope,elem,attrs) {
if(attrs.setAttr.indexOf('{') != -1 && attrs.setAttr.indexOf('}') != -1) {
//you could just angular.isObject(scope.$eval(attrs.setAttr)) for the above but I needed it this way
var data = scope.$eval(attrs.setAttr);
angular.forEach(data, function(v,k){
if(angular.isObject(v)) {
if(v.value && v.condition) {
elem.attr(k,v.value);
elem.removeAttr('set-attr');
}
} else {
elem.attr(k,v);
elem.removeAttr('set-attr');
}
});
}
}
}
});
Of course your can use dynamic versions built into angular:
<div ng-class="{ 'myclass' : item.iscool }"></div>
You can also use the new ng-if added by angularjs which basically replaces ui-if created by the angularui team these will conditionally add and remove things from the DOM and add watch listeners to keep evaluating:
<div ng-if="item.iscool"></div>
What also works is:
<span>{{ varWithValue || 'If empty use this string' }}</span>