I have email validation that has specific format ab123c#email.com or ab1234#email.com its validationg first 5 characters but not the complete email address using angularjs ng-pattern. How can i validate specific email address using angularjs ?
main.html
<div layout="row">
<md-input-container flex="100">
<label>Cc</label>
<input type="email" name="email" ng-model="notifyCtrl.cc" ng-list="," ng-pattern="pattern(user.type)">
<div class="help-block" ng-messages="notifyForm.email.$error" ng-show="notifyForm.email.$touched && notifyForm.email.$invalid">
<div ng-if="user.type === 'notify'">
<div ng-message="pattern">
An email name must only contain a-z, A-Z, 0-9, or _ characters.(ie. ab123c#tad.com, ab1234#tad.com
</div>
</div>
</div>
</md-input-container>
</div>
ctrl.js
var emailFormat = new RegExp('^[a-z]{2}[0-9]{3}[a-z0-9]$');
$scope.pattern = function(type){
if(type === 'notify') {
return emailFormat;
}
};
In your Input email you can use the following ng-pattern
ng-pattern="/^[_a-z0-9]+(\.[_a-z0-9]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/"
This is the best pattern to check valid email address:
ng-pattern='/^(([^<>()\[\]\\.,;:\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,}))$/'
You can try this another regex:
ng-pattern='/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/';
Related
I have this code to validate inputs:
<script>
function validate()
{
var firstName = document.form.fullname.value;
var lastName = document.form.fullname.value;
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword = document.form.conpassword.value;
if (firstName == null || firstName == "")
{
alert("Firstname can't be blank");
return false;
} else if (lastName == null || lastName == "")
{
alert("Lastname can't be blank");
return false;
} else if (email == null || email == "")
{
alert("Email can't be blank");
return false;
} else if (password.length < 6)
{
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
And this is my form:
<form name="form" action="<%=request.getContextPath()%>/register" method="post">
<div class="container">
<div class="left">
<div class="header">
<h2 class="animation a1">Register now</h2>
<h4 class="animation a2">Enter information in field and create account!</h4>
</div>
<div class="form">
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name...">
<input type="text" name="lastName" class="form-field animation a3" placeholder="Last name...">
<input type="email" name="email" class="form-field animation a3" placeholder="Email adress...">
<input type="password" name="password" class="form-field animation a4" placeholder="Password">
<button class="animation a6" value="Submit" type="submit">REGISTER</button>
</div>
</div>
<div class="right"></div>
</div>
</form>
How to implement that function to my form? Because now when I click submit, in my database an empty user is added. I want to add that it throws out an error in each field if it is not validly filled in
You can get the validate function to execute by adding an 'onsubmit' to your form html tag ( see here w3 Schools for executing a function on submit: onsubmit in forms)
As for the errors, when executing the code, the function cannot read a property 'value' of undefined. So what is happening is that you are telling the validate function to get parts out of the form out that it cannot find (fullname and conpassword are not defined).
Take a look at your form's name tags for fields and then reference those names in the validate function. So when declaring firstName instead of document.form.fullname.value try document.form.firstName.value referring in the form. Do this for first and last name using their names in the form, and also get rid of (or comment out) the conpassword variable.
This validation could be done without javascript function. Use the "required" tag for the inputs which are mandatory.
For example :
<input type="text" name="firstName" class="form-field animation a3" placeholder="Name..." required>
In case of password you may use the pattern attribute.
If you need to use javascript in particular, then go for onclick in the button tag.
<button class="animation a6" onclick="validate()">REGISTER</button>
and include the form submit in the javascript function -
document.form.submit();
I have a form with an option element on top and an email field.
<form class="form-versenden" action="mainVersendet.php" method="post" name="send">
<div class="form-group">
<h4>Bitte tragen Sie die folgenden Daten ein</h4>
<div class="form-group">
<label for="versandart">Versandart</label>
<select class="form-control" id="versandart" name="versandart" autofocus>
<option value="both">E-Mail und Druck</option>
<option value="onlyEmail">Nur E-Mail</option>
<option value="onlyPrint">Nur Druck</option>
</select>
</div>
<div class="form-group">
<label for="email">E-Mail</label>
<input type="email" class="form-control" id="email" placeholder="email" name="email">
</div>
<button class="btn" type="submit">Versenden</button>
</div>
</form>
Depending on what the user chooses, I have to check if an email address is entered in the case 'both' and 'onlyEmail'. Because email is not required in all 3 cases I can't use the required element of HTML for the email field. So I tried to test it on the submit event like this:
document.querySelector('form[name="send"]').addEventListener("submit", validateFields);
function validateFields(){
var versandart = document.getElementById("versandart");
var email = document.getElementById("email");
if (versandart.value == 'both' || versandart.value == 'onlyEmail'){
if(email.value == ''){
email.setCustomValidity('EMail muss eingegeben werden');
return false;
}else if(CHECK HERE if Mail is not correct){
email.setCustomValidity('EMail format is not correct');
return false;
}else{
//in this case email is not empthy and is correct
return true;
}
}
}
But this is not working because I overwrite the standard HTML check for a valid email address. So I have to check it again at the point 'CHECK HERE if Mail is not correct'.
How can I do that and is that the right way? Or should I add an onchangelistener to the versandart field and add the required tag to the email field if the selected value is fitting into the first two cases?
In your else if, use the isEmail() function like this:
else if(email.value.isEmail()) {
return true;
// Now the form will get submitted to the PHP script.
}
string.isEmail() returns true if the entered pattern matches an email address, otherwise false.
Please don't forget to do server side form validation, too, though. If a cracker switches JavaScript off, they may cause mayhem in your system if you only have JavaScript validation -- especially as you apparently can't use required HTML attribute for your email input.
Using Angular Reactive Form to validate password which as to match Password with atleast :
|*> 1 lowercase
|*> 1 uppercase
|*> 1 numeric
|*> 8 char longer
Using Reg Exp :
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})"
Html Code :
<form [formGroup]="NamFomNgs">
<label>Email :
<input type="email" name="MylHtm" formControlName="MylNgs">
</label><br>
<div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['MylNgs'].touched || NamFomNgs.controls['MylNgs'].dirty) &&
!NamFomNgs.controls['MylNgs'].valid">
<span *ngIf="NamFomNgs.controls['MylNgs'].errors.required">This field is required</span>
<span *ngIf="NamFomNgs.controls['MylNgs'].errors.email">Enter valid email</span>
</div><br>
<label>Password :
<input type="text" name="PwdHtm" formControlName="PwdNgs">
</label><br>
<div class="ErrMsgCls" *ngIf="(NamFomNgs.controls['PwdNgs'].touched || NamFomNgs.controls['PwdNgs'].dirty) &&
!NamFomNgs.controls['PwdNgs'].valid">
<span *ngIf="NamFomNgs.controls['PwdNgs'].errors.required">This field is required</span>
<span *ngIf="NamFomNgs.controls['PwdNgs'].errors.pattern">Enter valid password</span>
</div><br>
<button [disabled]="!NamFomNgs.valid">Submit</button>
</form>
TypeScript Code :
NamFomNgs:FormGroup;
constructor(private NavPkjVaj: ActivatedRoute, private HtpCncMgrVaj: HttpClient,private FomNgsPkjVaj: FormBuilder){
this.NamFomNgs = FomNgsPkjVaj.group(
{
MylNgs:[null,Validators.compose([
Validators.required,
Validators.email ])],
PwdNgs:[null,Validators.compose([
Validators.required,
Validators.pattern("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.{8,})")])]
});
}
Screen Shot of Output :
When I try with https://regex101.com/
The same reg exp shows valid for the requirments. But its invalid in Angular. Kindly help me with right way and to resolve this.
You have to capture something in your regex, you're only using positive look-ahead groups. Just change the length part like this :
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}"
I want to have a field in which users can type only numbers 0-9. In case they type other characters like '.' or 'e' it has to show an error that only positive natural numbers are allowed. Form is used in Angular.
So I have here the html form:
<div class="col-xl-8">
<input formControlName="money" type="number" class="form-control">
<span class="error" *ngIf="money?.errors?.pattern"> Natural numbers </span>
</div>
while pattern is
this.money = new FormControl('', [Validators.required, Validators.pattern('^[1-9][0-9]*$')]);
The pattern is just fine it allows numbers from 0 till 9 and it doesn't allow decimals or '.' or 'e'.
So the problem is that since input is type number it allows '.' and 'e' even though the pattern doesn't allow it and I can't submit it, the error message is not showed since the html validater is based on the type number thing.
Yet, inputs such as these are allowed and the error label does not appear:
1.....2
......
eeee........
1.0.0.01.0
And so on.
So what should I do to show the error label when '.' or 'e' are typed?
Use ng-pattern directive directly?
<div class="col-xl-8">
<input formControlName="money"
type="number"
ng-pattern="^[1-9][0-9]*$')]"
class="form-control">
<span class="error" *ngIf="money?.errors?.pattern"> Natural numbers </span>
</div>
And tie validation to $valid of that input myForm.myInput.$valid
Use following code:
<div class="col-xl-8">
<input [formControl]="money"
type="number"
class="form-control">
<span class="error" *ngIf="money.dirty && money?.errors?.pattern"> Natural numbers </span>
</div>
In your ts file update regex ^[1-9][0-9]{1,3}
Hope it will help
In .ts file :
export class ReactiveFormExampleComponent{
reactiveForm: FormGroup;
constructor(private fb: FormBuilder) {
this.reactiveForm = fb.group({
money: ['', [Validators.required, Validators.pattern('^[1-9][0-9]*$')]]
});
}
onSubmit() {
alert("Form submitted");
}
}
html file
<form [formGroup]="reactiveForm" (ngSubmit)="onSubmit()" nonvalidate>
<div>
<label class="center-block">Money:
<input type="number" class="form-control" formControlName="money">
</label>
<span [hidden]="reactiveForm.controls.money.valid || reactiveForm.controls.money.pristine" class="errorMsg">Natural numbers only</span>
</div>
<button type="submit" [disabled]="reactiveForm.invalid" class="btn btn-success">Save</button>
</form>
NOTE : Don't forget to import 'ReactiveFormsModule' in NgModule.
Here is working plunker check it out here.
I have a ng-pattern validation for a regex of ^[^\./:*\?\"<>\|]{1}[^\/:*\?\"<>\|]{0,254}$ which basically tests the invalid chars in filepath and teh limit. but when i have the ng-pattern specified as
ng-pattern = "^[^\\\./:\*\?\"<>\|]{1}[^\\/:\*\?\"<>\|]{0,254}$"
, the ng-pattern shows the regex in an incorrect way. any help on achieving this correctly
First of all, your regex contains too many escaping symbols, while you only need to escape the " here and \\.
Then, to match a " inside ng-pattern attribute, you may define it as \x22 or ":
var app = angular.module("app", []);
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<form name="form">
<p>Enter text to validate:</p>
<input type="text" ng-model="name" name="name" ng-pattern="/^[^\\\\./:*?"<>|][^\\\\/:*?\x22<>|]{0,254}$/" ng-trim="false" />
<div ng-show="form.name.$error.pattern">Text doesn't match with ng-pattern!</div>
</form>
</body>
</html>
You may also solve the problem by defining a regex in the controller with a regular string literal where you may use '.."..' or "..\"...", and then use the variable name inside {{...}} in the ng-pattern attribute. Note that to match a literal \ you need to use 4 backslashes in the regex pattern.
var app = angular.module("app",[]);
app.controller("FormCtrl", function($scope) {
$scope.regex = "/^[^\\\\./:*?\"<>|][^\\\\/:*?\"<>|]{0,254}$/";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<form name="theForm" ng-controller="FormCtrl" novalidate>
<input type="text" name="filename" placholder="filename" ng-model="filename" ng-pattern="{{regex}}" required />
<div class="error"
ng-show="(theForm.filename.$dirty || attempted) && theForm.filename.$invalid">
<small class="error text-danger"
ng-show="theForm.filename.$error.required">
Please enter a file name.
</small>
<small class="error text-danger"
ng-show="theForm.filename.$error.pattern">
Please enter a valid file name.
</small>
</div>
</form>
</div>
I was trying to exclude ' and " in a ng-pattern which is similar to the problem above. I found a way to embed ' or " directly without having to use a scope variable:
<input type="text" ng-pattern="/^[^"']+$/" />
You can use \" to escape ".