Do HTML email validation and Angular 2 work together? - html

I'm currently working on validations with Angular 2. I have some problems with HTML email and website validators and valid ngModel's property.
For example:
<form #form="ngForm">
<input type="email" #email="ngModel" [(ngModel)]="contact.email" name="email" >
<button [disabled]="!form.form.valid" type="submit">Btn</button>
Every word i input is fine. #email.valid remains true as if no HTML5 validator existed:
{{#email.valid}} %%% true
So the form's button is enabled all the time. But when I hit the button the HTML warning comes out saying that the email field is invalid, so validation is working, but #email.valid it's still true.
Is it possible to use angular2's ngModel directive with HTML validators?

Yes you can use both together, you can use them like this:
<input id="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" class="form-control" type="email" ng-model="loginctrl.user.email" name="email" placeholder="Enter Email Address" required/>
<span ng-show="myForm.email.$touched && myForm.email.$error.required"><b class="color">This is a required field</b></span> <span ng-show=" myForm.$dirty && myForm.email.$invalid"><b class="color">This field is invalid</b></span>

Related

html5 e-mail validation failed

I have this simple input field for e-mail addresses:
<form>
<input type="email" placeholder="E-Mail" required>
<input type="submit" value="Send" />
</form>
If you write "max#mail.de", you can submit the form, because the email is valid.
If you write "max#.de", you can't submit the form, because the email is invalid.
But!
If you write "max#i9", you can submit the form, too. But the mail is invalid. Why?
And how can I fix it?
Because max#i9 is a valid email as it stated in this article.
You can "fix" it by adding your own email pattern, see this tutorial:
<form>
<input type="email" pattern="/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/" required />
</form>
Here's a more detailed question about Why does HTML5 form validation allow emails without a dot?
<form>
<input pattern="[a-zA-Z0-9.-_]{1,}#[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}$"
type="text" required />
<input type="submit" value="Send" />
</form>
This is because HTML5 type="email" validator is only find # symbol in your input string. If it is found your form will submitted else it won't submitted.
To avoid this you have to use javaSctipt form Validation like this :-
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("#");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
HTML can't help you with data validation, you can learn js to do that

How to prevent repetition in Angular html?

I have an input in my html as follows:
<ng-container *ngIf="({required: <some_condition>, invalid: <some_condition>}) as emailErrors">
<input type="email" class="form-control" placeholder="Email" validate-onblur [class.is-invalid]="emailErrors.required || emailErrors.invalid" [attr.aria-invalid]="emailErrors.required || emailErrors.invalid" [attr.aria-describedby]="emailErrors.required || emailErrors.invalid ? 'email-error' : undefined">
<div *ngIf="emailErrors.required" id="email-error">
<p class="error-msg">{{messages.EMAIL_REQ}}</p>
</div>
</ng-container>
Here in my <input> tag I'm repeting this condition 3 times: emailErrors.required || emailErrors.invalid.
Can I store this condition here in a variable, so that I do not have to repeat it?
P.S. I'm new in Angular
I would recommend you to use the template form of Angular. These are fairly simpler to implement.
In the code below make sure you give name property on the input field otherwise an error will be thrown, while working on with [(ngModel)]
<form #f="ngForm">
<input type="email" class="form-control" placeholder="Email" name="mail" required [(ngModel)]="model.email" #mail="ngModel">
<span *ngIf="mail.invalid">
{{messages.EMAIL_REQ}}
</span>
</form>
Why not introduce an additional property in the wrapping <ng-container>? And seeing that emailErrors.invalid isn't used anywhere else, it could be removed if it's unneeded.
<ng-container *ngIf="({required: <condition_1>, reqOrInv: <condition_1> || <condition_2>}) as emailErrors">
<input
type="email"
class="form-control"
placeholder="Email"
validate-onblur
[class.is-invalid]="emailErrors.reqOrInv"
[attr.aria-invalid]="emailErrors.reqOrInv"
[attr.aria-describedby]="emailErrors.reqOrInv ? 'email-error' : undefined"
>
<div *ngIf="emailErrors.required" id="email-error">
<p class="error-msg">{{messages.EMAIL_REQ}}</p>
</div>
</ng-container>
But as #YashwardhanPauranik noted in their answer, you're better off using Angular template driven or reactive forms. They provide more granular control.

Angular JS custom textbox from a list validation

I am creating dynamic textboxes from a list like the following
Angular js
$scope.phonenumbers = [{text: ''},{text: ''},{text: ''}];
HTML Part
<div class="relativeWrap" ng-repeat="phone in phonenumbers">
<input placeholder="Phone Number" pattern="[0-9]{10}" ng-maxlength="10" maxlength="10" type="text" class="form-control input-text phone_number" name="phonenumber[]" ng-model="phone.text" >
</div>
Now I need to do the following validation in form
Any one of the following 3 textboxes is mandatory. I put required but it is validating all.
Please help
You will need to use ng-required and conditionally set the required to true for all the field only when none of the fields have a value. To do this you will need to maintain a flag in your controller and bind that your ng-required.
The method in the controller:
$scope.isValue = false;
$scope.textChange = function(){
$scope.isNoValue = $scope.phonenumbers.some(function(item)){
return item.text;
}
}
Your HTML:
<div class="relativeWrap" ng-repeat="phone in phonenumbers">
<input placeholder="Phone Number" pattern="[0-9]{10}" ng-maxlength="10" maxlength="10" type="text" class="form-control input-text phone_number" name="phonenumber[]" ng-model="phone.text" ng-required="!isValue" ng-change="textChange">
</div>

Html 5 Form validation without Form

Can a html5 form validation
<form>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</form>
can it be done without a Form
<div>
<input type="email" id="email" placeholder="Enter your email here..." required>
<button type="submit">Submit</button>
</div>
Yes, use the constraint validation API. See http://www.w3.org/TR/html5/forms.html#the-constraint-validation-api. For instance, you can call element . checkValidity(). See also https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation or https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/checkValidity. For example:
var email = document.getElementById('email');
var valid = email . checkValidity();
if (!valid) ...
or use the invalid event which is fired when checkValidity() fails:
email.addEventListener("invalid", function() { alert("Email invalid"); });
You can use setCustomValidity to set the validity status and/or error message:
if (!email.value) email.setCustomValidity("Email is missing");
If you want to see the errors in the page, instead of just receiving a boolean with the validation result, you can use:
document.gelElementById('email').reportValidity();

How can I change or remove HTML form validation default error messages?

For example I have a textfield. The field is mandatory, only numbers are required and length of value must be 10. When I try to submit form with value which length is 5, the default error message appears: Please match the requested format
<input type="text" required="" pattern="[0-9]{10}" value="">
How can I change HTML form validation errors default messages?
If the 1st point can be done, is there a way to create some property files and set in that files custom error messages?
This is the JavaScript solution:
<input type="text"
pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Please enter Alphabets.')"
onchange="try{setCustomValidity('')}catch(e){}" />
The "onchange" event needs when you set an invalid input data, then correct the input and send the form again.
I've tested it on Firefox, Chrome and Safari.
But for Modern Browsers:
Modern browsers didn't need any JavaScript for validation.
Just do it like this:
<input type="text"
pattern="[a-zA-Z]+"
title="Please enter Alphabets."
required="" />
When using pattern= it will display whatever you put in the title attrib, so no JS required just do:
<input type="text" required="" pattern="[0-9]{10}" value="" title="This is an error message" />
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Plz enter on Alphabets ')" />
I found this code in another post.
HTML:
<input type="text" pattern="[0-9]{10}" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" />
JAVASCRIPT :
function InvalidMsg(textbox) {
if(textbox.validity.patternMismatch){
textbox.setCustomValidity('please enter 10 numeric value.');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Fiddle Demo
To prevent the browser validation message from appearing in your document, with jQuery:
$('input, select, textarea').on("invalid", function(e) {
e.preventDefault();
});
you can remove this alert by doing following:
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity(' ')"
/>
just set the custom message to one blank space
you can change them via constraint validation api: http://www.w3.org/TR/html5/constraints.html#dom-cva-setcustomvalidity
if you want an easy solution, you can rock out civem.js, Custom Input Validation Error Messages JavaScript lib
download here: https://github.com/javanto/civem.js
live demo here: http://jsfiddle.net/hleinone/njSbH/
The setCustomValidity let you change the default validation message.Here is a simple exmaple of how to use it.
var age = document.getElementById('age');
age.form.onsubmit = function () {
age.setCustomValidity("This is not a valid age.");
};
I Found a way Accidentally Now:
you can need use this: data-error:""
<input type="username" class="form-control" name="username" value=""
placeholder="the least 4 character"
data-minlength="4" data-minlength-error="the least 4 character"
data-error="This is a custom Errot Text fot patern and fill blank"
max-length="15" pattern="[A-Za-z0-9]{4,}"
title="4~15 character" required/>
I found a bug on Mahoor13 answer, it's not working in loop so I've fixed it with this correction:
HTML:
<input type="email" id="eid" name="email_field" oninput="check(this)">
Javascript:
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!");
}
else {
input.setCustomValidity("");
}
}
It will perfectly running in loop.
This is work for me in Chrome
<input type="text" name="product_title" class="form-control"
required placeholder="Product Name" value="" pattern="([A-z0-9À-ž\s]){2,}"
oninvalid="setCustomValidity('Please enter on Producut Name at least 2 characters long')" />
To set custom error message for HTML validation use,
oninvalid="this.setCustomValidity('Your custom message goes here.')"
and to remove this message when user enters valid data use,
onkeyup="setCustomValidity('')"
As you can see here:
html5 oninvalid doesn't work after fixed the input field
Is good to you put in that way, for when you fix the error disapear the warning message.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')" />