I am having a problem verifing the the password entered in my angular 2 form contains at least one number in it. The other validators work its just this pattern one. the regex I am using I got from
Regex: Check if string contains at least one digit
Password:
<div *ngIf="signUpForm.controls['password'].invalid && signUpForm.controls['password'].dirty">
<small *ngIf="signUpForm.controls['password'].errors.minlength">
Please enter a minimum of 6 characters
</small>
<small *ngIf="signUpForm.controls['password'].errors.maxlength">
Password cannot exceed 15 characters
</small>
<small *ngIf="signUpForm.controls['password'].errors.pattern">
Must contain digits
</small>
</div>
inside my form I have the following validator and specifically the pattern I want is to check if the string entered contains a number
"password":["", [
Validators.required,
Validators.minLength(6),
Validators.maxLength(15),
Validators.pattern('/\d')
]
]
The errors.patters ngIf never goes away even if there are numbers in the field, not sure what I am doing wrong. My other pattern validators for other fields work.
How about Validators.pattern('\\d+')?
If I understand this correctly, you would need to provide a backslash (not forward slash) to escape the backslash.
Written as a regular expression literal this would look like /\d+/, but I don't think Angular 2 supports those.
UPDATE If that's not working then it must be either something with your setup or a bug in Angular 2. I don't use Angular 2 personally so hard to say but you can see the regex itself is fine:
const regex = new RegExp('\\d+', 'g')
console.info('hiwefwe883290awefoijwfe8382jfwef'.match(regex))
Your pattern \d will only work for a single digit. You need to add a quantifier.
\d+
That will match one or more digits but not a blank value.
Related
I have an input field in my Angular component in which i want to not allow a user to be able to type a (space).
I've tried using
<input type="text" [(ngModel)]="inputText" pattern="[a-zA-Z]">
which wasn't what i wanted, and it didn't work anyways!
Does anybody know what the correct regex pattern to just block the (space) key is? And what is the correct way to use the pattern, as the above pattern didn't work...
Thanks in advance.
Using RegEx will still allow the user to type in space. But it will mark the field as invald if a pattern validator is applied to it.
If you don't really want to allow the user to type in space in the first place, you'll have to prevent it by listening to the keydown event on the input and then handling it to prevent its default behaviour. Here, give this a try:
<input type="text" (keydown.space)="$event.preventDefault()">
Here's also a Sample StackBlitz for your ref.
If you want to allow any type of character except spaces alone without any letters, you can use this:
"^\w+( +\w+)*$"
If you also want to use accented vowels, you can use this:
"^[a-zA-Zá-úÁ-Ú0-9]+( +[a-zA-Zá-úÁ-Ú0-9]+)*$"
You can use the following pattern:
<input pattern="[^\s]*">
[^\s] is a negative set which matches every character which is not in the set.
\s matches a white space character (e.g. space, tab, etc.)
* matches 0 or more character of the preceding item
Here is an example of how the browser checks if the pattern is correct (i.e. Google Chrome for example does not allow you to submit the form if there is a whitespace character in it. Test it here (enter a string containing a white space and hit Submit):
<form>
<input pattern="[^\s]*">
<button type="submit">Submit</button>
</form>
The best way of addressing this problem is by writing the directive which you can use on multiple locations.
Here is the Stackblitz sample for the same
I want to extract data from html. The thing is, that i cant extract 2 of strings which are on the top, and on the bottom of my pattern.
I want to extract 23423423423 and 1234523453245 but only, if there is string Allan between:
<h4>###### </h4> said12:49:32
</div>
<a href="javascript:void(0)" onclick="replyAnswer(##########,'GET','');" class="reportLink">
report </a>
</div>
<div class="details">
<p class="content">
Hi there, Allan.
</p>
<div id="AddAnswer1234523453245"></div>
Of course, i can do something like this: Profile\/(\d+).*\s*.*\s*.*\s*.*\s*.*\s*.*\s*.*\s*.*Allan.*\s*.*\s*.*AddAnswer(\d+). But the code is horrible. Is there any solution to make it shorter?
I was thinking about:
Profile\/(\d+)(.\sAllan)*AddAnswer(\d+)
or
Profile\/(\d+)(.*Allan\s*)*AddAnswer(\d+)
but none of wchich works properly. Do you have any ideas?
You can construct a character group to match any character including newlines by using [\S\s]. All space and non-space characters is all characters.
Then, your attempts were reasonably close
/Profile\/(\d+)[\S\s]*Allan[\S\s]*AddAnswer(\d+)/
This looks for the profile, the number that comes after it, any characters before Allan, any characters before AddAnswer, and the number that comes after it. If you have single-line mode available (/s) then you can use dots instead.
/Profile\/(\d+).*Allan.*AddAnswer(\d+)/s
demo
You can use m to specify . to match newlines.
/Profile\/(\d+).+AddAnswer(\d+)/m
Better use a parser instead. If you must use regular expressions for whatever reason, you might get along with a tempered greedy solution:
Profile/(\d+) # Profile followed by digits
(?:(?!Allan)[\S\s])+ # any character except when there's Allan ahead
Allan # Allan literally
(?:(?!AddAnswer)[\S\s])+ # same construct as above
AddAnswer(\d+) # AddAnswer, followed by digits
See a demo on regex101.com
I need to combine these 2 patterns together or use them both in my <input> field
I have pattern matching to check for a valid time - which works great and the field is "NOT REQUIRED" so we will accept a blank field
pattern="([01]?[0-9]|2[0-3])[0-5][0-9]"
I also want to use this pattern to allow null values OR a max and min length of only 4 characters...
pattern=".{0}|.{4,4}"
I also have maxlength set - might be redundant
maxlength="4"
So basically I need a fixed character length (time as HHMM) of 4 characters or null - nothing in between....
I would have just been happy to use minlength but am receiving conflicting reports about its acceptance among browsers...
<input type="text" name="movie" maxlength="4" pattern="([01]?[0-9]|2[0-3])[0-5][0-9]" pattern=".{0}|.{4,4}" value='<?php echo $objResult["MOVIE"]; ?>'>
Try the following pattern:
(?:([01]?[0-9]|2[0-3])[0-5][0-9]|^$)
Which says: your pattern or an empty string (the ^$ part).
Hint: did not verify your pattern, just to give you an idea of the concept.
You have an optional digit in the first group: [01]?. It makes it possible to enter only 3 digits (leading 0 is optional).
Now, I understand you want to make the 0 obligatory and add a possibility to use an empty value. Just remove the ? quantifier from [01]? and use
<input pattern="(([01][0-9]|2[0-3])[0-5][0-9])?" title="4 digits please!" placeholder="0000"/>
The outer ()? makes the whole pattern optional (one or zero occurrences).
input:valid {
color: green;
}
input:invalid {
color: red;
}
<form name="form1">
<input pattern="(([01][0-9]|2[0-3])[0-5][0-9])?" title="4 digits please!" placeholder="0000"/>
<input type="Submit"/>
</form>
Note: HTML5 pattern attribute value is anchored by default, i.e. the whole pattern is wrpapped into ^(?: and )$. You do not have to put ^ and $ between the pattern, and even if you add an alternative as Jan did, you do not need the ^/$ around the empty value.
The regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a ^(?: at the start of the pattern and a )$ at the end).
I am trying to get an angular ng-pattern to check that a username has no whitespaces or special characters. The following form return false if you enter whitespaces or special characters. However, it becomes true as soon as you enter a-z, A-z or 0-9. I have tried ng-pattern="/[^\s]+/" and \S and [^ ] but they make no difference.
<form name="myform">
valid? {{ myform.$valid }}
<input type="text" name="username" ng-model="username" ng-pattern="/[a-zA-Z0-9^ ]/" required/>
</form>
Here's the form in a plunk: http://plnkr.co/edit/6T78kyUgXYfNAwB4RHKQ?p=preview
Try the following pattern:
/^[a-zA-Z0-9]*$/
This allows only alphanumeric characters.
To surface the specific answer I was looking for, I already had the pattern suggested by Sniffer /^[a-zA-Z0-9]*$/, but angular still appeared to ignore leading/trailing whitespace. As Cristian mentions in the comments:
Angular will trim the input model, meaning that the validation doesn't trigger for spaces. You can add an ng-trim="false" to the input to fix this.
Note that Angular is trying to protect you by silently trimming whitespace by default. In my case, I want the user to be aware that the trailing whitespace is invalid.
in case anyone needs to disallow user entering emails in the address field
ng-pattern="/^[^#]+$/"
<div ng-messages="vm.updateCC.mailingAddress.$error" ng-show="vm.updateCC.mailingAddress.$touched">
<p class="validation-message" ng-message="pattern">Please enter a valid address</p>
</div>
I am just starting to test out ng-pattern with some regular expressions that I have used in non-Angular projects and have worked fine. But using ng-pattern they don't seem to work. For example I have this regular expression that successfully checks for a string of 6-20 characters with at least 1 alphabetical and 1 numeric character :
"^.*(?=.{6,20})(?=.*\d)(?=.*[a-zA-Z]).*$"
However, in my Angular example below it checks everything successfully except it is not triggered when the string goes beyond 20 characters :
<div class="controls">
<input type="text" ng-model="user.Password" id="Password" name="Password" title="Password" required ng-pattern="^/.*(?=.{6,20})(?=.*\d)(?=.*[a-zA-Z]).*$/" />
<span ng-show="form.Password.$dirty && form.Password.$error.required">{{'_PasswordRequired_' | i18n}}</span>
<span ng-show="form.Password.$dirty && form.Password.$error.pattern">{{'_PasswordLengthAndAlphanumeric_' | i18n}}</span>
</div>
Is there some error I am making in the syntax, or is there some other reason this is not working?
You're missing an end anchor, and you have one .* too many (at the start):
^ # Start of string
.* # Match *any* number of characters
(?=.{6,20}) # *Then* check that 6-20 characters follow
<snip>
.* # *Then* match any number of characters anyway
$ # until the end of the string
This would work:
"^(?=.{6,20}$)(?=.*\d)(?=.*[a-zA-Z]).*$"
But it would be easier (and more obvious) to do the length check outside of the lookahead anyway:
"^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$"
(which in turn makes me ask why you're imposing such a low upper limit? My KeePass-generated passwords are usually at least 30 characters in length, for example)