Form Validation with Bootstrap 4 beta - javascript

I'm having a problem with understanding the building validation forms. In bootstrap current documentation there is a piece of JS code (so called starter code):
<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
'use strict';
window.addEventListener('load', function() {
var form = document.getElementById('needs-validation');
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
}, false);
})();
</script>
and it works fine but what should I do if i want to implement password check, for example? If i inderstand it right Bootstrap has css classes :valid and :invalid which run when the field is empty. I want to fire them when some condition is the (ie password less than 8 symbols).
<form id="needs-validation" novalidate>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputPassword1">Password</label>
<input type="password" class="form-control" name="inputPassword1" id="pass1" placeholder="password" required>
<div class="invalid-feedback">
Please provide a valid password.
</div>
</div>
</form>

You could use the pattern attribute. From MDN:
pattern
A regular expression that the control's value is checked
against. The pattern must match the entire value, not just some
subset. Use the title attribute to describe the pattern to help the
user. This attribute applies when the value of the type attribute is
text, search, tel, url, email, or password, otherwise it is ignored.
The regular expression language is the same as JavaScript RegExp
algorithm, with the 'u' parameter that makes it treat the pattern as a
sequence of unicode code points. The pattern is not surrounded by
forward slashes.
For example, the following will validate that the password is at least 8 characters with upper case, lower case and numbers:
<form id="needs-validation" novalidate>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputPassword1">Password</label>
<input type="password" class="form-control" name="inputPassword1" id="pass1" placeholder="password"
pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$"
required>
<div class="invalid-feedback">
Passwords should be a minimum of 8 characters and include at least one upper case letter, one lower case letter and one number.
</div>
</div>
</form>

Related

Can someone suggest an HTML oninvalid Event Attribute work around in the context of my code?

Does anyone have a work around for Safari and google chrome for the HTML oninvalid Event Attribute not correctly working? In the context of my application, within the name field at first, I inputted an invalid answer which was a number, then after I corrected the answer to a valid input. However, the input "ededde" didn't work which is a valid input that should be accepted. Here is my demonstration video. Maybe I made a syntax error or the attribute isn't supported anymore?
What alternative method could I use, which would allow me to manually customise the error message for each input field and correctly work when the user changes their input from invalid to valid? I saw one solution one stack overflow, but the solution didn't cover multiple different input fields like my example code.
In additon, I was also reading another post and I saw someone wrote a JS script but the code appeared to be very complex for this sort of task. Therefore, I thought in the context of my code to get some guidance I would make this post as I'm really having trouble overcoming this glitch, unsupported attribute problem or a syntax error which I possibly made.
Below is my code which is relevant to the issue, if you need to see more let me know.
MY CODE
<div class="mb-3 text-white">
<label>Name</label>
<input
type="text"
name="name"
pattern="[A-Za-z]"
oninvalid="alert('NAME ERROR: Please eneter characters only.');" required>
</div>
<div class="mb-3 text-white">
<label>Barcode</label>
<input
type="text"
name="barcode"
oninvalid="alert('BARCODE ERROR: Please input barcode here.');" required>
</div>
<div class="mb-3 text-white">
<label>Email</label>
<input
type="email"
name="email"
oninvalid="alert('EMAIL ERROR: Please input email here.');"
required
>
</div>
That is because your pattern only accepts a single alphabet: [A-Za-z]. To accept an alphabetical string that has length of 1 or more, you need to add a + at the end, i.e. [A-Za-z]+:
// This JS is only for demo purposes, so that a successful validation will not submit the form in the demo snippet
document.querySelector('#my-form').addEventListener('submit', e => {
console.log('Form valid! Will submit, but submission is prevented for demo purposes');
e.preventDefault();
});
<form id="my-form">
<div class="mb-3 text-white">
<label>Name</label>
<input type="text" name="name" pattern="[A-Za-z]+" oninvalid="alert('NAME ERROR: Please eneter characters only.');" required>
</div>
<button>Submit</button>
</form>
On a side note, I strongly suggest not using inline JS. What you want to do can be easily done in JS: and you can also store the intended error message in data- attributes for convenience:
// This JS is only for demo purposes, so that a successful validation will not submit the form in the demo snippet
document.querySelector('#my-form').addEventListener('submit', e => {
console.log('Form valid! Will submit, but submission is prevented for demo purposes');
e.preventDefault();
});
document.querySelectorAll('input').forEach(el => {
const invalidMessageElement = el.nextElementSibling;
el.addEventListener('invalid', () => {
invalidMessageElement.textContent = el.dataset.invalidMessage;
invalidMessageElement.classList.add('visible');
});
el.addEventListener('input', () => {
invalidMessageElement.textContent = '';
invalidMessageElement.classList.remove('visible');
});
});
.invalid-message {
display: none;
color: red;
}
.invalid-message.visible {
display: inline;
}
<form id="my-form">
<div class="mb-3 text-white">
<label>Name</label>
<input type="text" name="name" pattern="[A-Za-z]+" required data-invalid-message="Please enter characters only."><span class="invalid-message"></span>
</div>
<div class="mb-3 text-white">
<label>Barcode</label>
<input type="text" name="barcode" required data-invalid-message="Please input barcode here."><span class="invalid-message"></span>
</div>
<div class="mb-3 text-white">
<label>Email</label>
<input type="email" name="email" required data-invalid-message"Please input email here."><span class="invalid-message"></span>
</div>
<button>Submit</button>
</form>

A field of Angular template driven forms considered invalid even though the regExp matches

I have this input:
<div class="form-group">
<label for="power">Hero Power</label>
<input [(ngModel)]="model.powerNumber" name="powerNumber" type="text"
class="form-control" pattern="^[0-9]+$"id="powerNumber">
<div [hidden]="powerNumber.valid" class="alert alert-danger">
power must be a number
</div>
</div>
I have added a pattern validator to the input field (only number should pass the test). Below the input I have added an error message that should hidden when the input field is valid. However it shows even when I have entered a value that matches the pattern RegExp. What am I doing wrong?
Here is a Stackblitz demonstration https://stackblitz.com/edit/template-driven-form-demo-wl3apt?file=app%2Fuser-form%2Fuser-form.component.ts
add #powerNumber="ngModel" template reference to input ngModel and all will be working. It is already done with name input in your example
I don't know whether it is eligible for you, however you can use input just for numbers:
<input [(ngModel)]="model.powerNumber" name="powerNumber" type="number"
class="form-control" id="powerNumber">

In ngTagsInput how to show validation message for different cases?

I am using ngTagsInput Angular plugin for getting multiple email ids. Below is my code:
<form name="contact_us" role="form" novalidate enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="from_email">
From
</label>
<tags-input ng-model="contactUs.emails" type="email" id="from_email"
placeholder="From" name="from_email"
allowed-tags-pattern="^[A-Za-z0-9._%+-]+#(?:[A-Za-z0-9-]+.)+[A-Za-z]{2,}"
allow-leftover-text="false" ng-required="true" add-on-space="true">
</tags-input>
<p class="help-block" style="color:red"
ng-show="contact_us.from_email.$invalid && (contact_us.$submitted || contact_us.$dirty)">
Please enter proper email address
</p>
<button type="submit" class="btn btn-default" ng-click="Send(contact_us)">
Send
</button>
</form>
In above code 3 validation has been added those are as follows:
For Mandatory fields.
Field should accept only an email id.
It should not allow duplicate email id.
The above cases are working fine. But, I want to show the error message dynamically according to the above one of the case has occurred. Please help me out !!!
ngTagsInput supports attribute below for change to capture, it fires before adding to model
on-tag-adding="foo($tag)"
$scope.foo(function(tag){
// look for error
// if found return false
// change the text of tag
tag.text='what ever';
return tag;
})
For required:
<p class="help-block" style="color:red"
ng-show="contact_us.from_email.$error.required">
email address is required
</p>
For pattern & duplicate, I think no validation flag has been provided and you have to write your own to perform validation.
For duplicate, maybe this will help.
Angularjs - How to check for unique inputs and if there is a duplicate mark both as invalid

What is the regular expression for username shouldn't be root

What I tried
^((?!root).)*$
Results
root invalid username
admin valid username
rootwee invalid username (this should be valid)
root123 invalid username (this should be valid)
I tried removing . from regex, then its not working
Can you please help with this?
Your regex features a tempered greedy token that disallows a certain substring in the whole input. Thus, "rootwee" and "root123" are invalid.
You can use
/^(?!root$)/
See demo
The anchored lookahead (?!root$) makes sure the whole input is not equal to root, but the string itself can contain root.
Note that when using a literal regex declaration, we needn't match the whole input string.
Here is a demo snippet:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="text" name="field" ng-model="formCtrl" ng-pattern="/^(?!root$)/" required>
<span ng-show="myForm.field.$error.pattern">Not valid!</span>
<span ng-show="myForm.field.$error.required">This field is required!</span>
<input type="submit" value="submit"/>
</form>
</div>

email regular expression does not validate the part after period

I am trying to validate email address in my html page using angular directive.
To me valid email address is
hello#mycompany.com
The following regular expression allows following email address
hello#mycompany
What kind of regular expression I could use that would also enforce the ".com" part of email address meaning enforce "." and any thing after "."
I have researched internet and used different listed regular expression but none are working
<div class="form-group" ng-class="{ 'has-error': registerUpdateForm.Email.$invalid }">
<label class="col-sm-3 control-label" for="Email">Email Address</label>
<div class="col-sm-9">
<input required type="email" data-ng-model="auth.Email"
data-ng-pattern="^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"
id="email" name="Email" class="form-control" /> <!--ng-pattern="matchPattern"/>-->
</div>
</div>
The expected value is a Regexp or an inline pattern, which in javascript looks like /pattern/. The regular expression itself looks good, so just try adding the forward slashes at the beginning and end:
<input required type="email" data-ng-model="auth.Email"
data-ng-pattern="/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/"
id="email" name="Email" class="form-control" />
Plunker Demonstration
The W3C specification for <input type="email"> says that the email address must match the regex
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
so that would be a reasonable start on something like (untested)
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+\.com$/
Note that you can't restrict the top-level domain to {2,4} characters any more, if you want to allow more than just ".com": Proposed domains.

Categories

Resources