VeeValidate multiple password constraints - validation

I'm wondering if it's possible to have multiple password requirements passed to VeeValidate in order to display which requirements a user is missing.
For instance, if we require that a user's password should have at least one uppercase letter and at least one number and be at least 5 characters long, and the user types in "a1bb", we'd like to be able to display two error messages; one associated with the length requirement not being met and one related to the uppercase requirement not being met.
Ultimately, we'd like to be able to do something like this:
Would that be possible with VeeValidate? Or are there any examples of a similar approach?

VeeValidate allows you to display multiple errors fields but you need to disable the fastExist config option first:
VeeValidate only generates one message per field by default as it uses
a fast-exit strategy when running the validation pipeline. [...] To disable this behavior you may want to configure the
fastExit option in VeeValidate's config or use the continues modifier. (source)
For the rules you want to apply to password, you can use the existing min rule for the minimum length.
For the other rules (check upcase, lowercase, special char and digit), it's about regex check. VeeValidate actually provides a regex rule but in your case you need multiple ones.
So you need to define custom rules. I put some examples in the snippet below in the created hook but you also can define them globally.
In my example, I create a method to return a css class error by checking the errors by rule name.(source)
Now the style is yours.
const config = {
fastExit: false
}
Vue.use(VeeValidate, config)
new Vue({
el: "#app",
data() {
return { password: '' }
},
created() {
this.$validator.extend('upCase', {
getMessage: () => "One uppercase character",
validate: value => value.match(/[A-Z]/g) !== null
})
this.$validator.extend('number', {
getMessage: () => "One number",
validate: value => value.match(/[0-9]/g) !== null
})
},
methods: {
errorClass(rule) {
return {
'error': this.errors.firstByRule('password', rule)
}
}
}
})
li {
color: #B1B1B1;
}
li.error {
color: #262626;
}
<script src="https://unpkg.com/vue#2.6.8/dist/vue.min.js"></script>
<script src="https://unpkg.com/vee-validate#2.0.0-rc.19/dist/vee-validate.js"></script>
<div id="app">
<input type="text" v-validate="'min:8|number|upCase'" name="password" >
<ul>
<li :class="errorClass('upCase')">One uppercase character</li>
<li :class="errorClass('number')">One number</li>
<li :class="errorClass('min')">8 characters minimum</li>
</ul>
</div>

check this solution
make a custom rule form VEEVALIDATE
STRONG PASSWORD VALIDATION
http://frankclark.xyz/veevalidate-strong-password-and-confirmation-validation

Related

Dynamic pattern validation in Angular 2 and 4

Input validation works fine with a fixed pattern, e.g.
<input type="number"
[(ngModel)]="info.sortOrder"
pattern="[0-9][0-9]"
id="sortOrder" name="sortOrder" #sortOrder="ngModel"/>
When changing the pattern to be evaluated through a function, validation always fails. The function "customPattern()" is called, though.
<input type="number"
[(ngModel)]="info.sortOrder"
[pattern]="customPattern()"
id="sortOrder" name="sortOrder" #sortOrder="ngModel"/>
With
customPattern() { return "[1-9][0-9]"; }
Is this a bug or is this not supposed to work this way?
I guess you are dong wrong, #black
I would recommend you to use Reactive Forms approach to achieve the desire result.
create a reactive form.
Add the control name for eg('number_validation').
(optional) Register the HTML input element with the formControlName same as above ('number_validation').
create a field 'regex' = '[0-9][0-9]' in the component.ts file.
Bind the [pattern] = regex in the HTML HTML input element tag.
Listen the change and change the regex pattern according to the requirement.
In ts file.
someForm: FormGroup;
this.someForm= new FormGroup({
'some_name': new FormControl('', [
Validators.required])});
regex = /[0-9][0-9]/;
In HTML:
<input type="number"
[pattern]=regex
id="sortOrder"
formControlName=some_name
name="sortOrder"/>
Logic :
It depends on the requirement how you are going to change the regex value, dynamically.
eg.
ngAfterViewInit() {
this.someForm.get('some_name').valueChanges.subscribe(val => {
if (val === 'anything') {
this.regex = /change the regex/;
} else if (val === 'anything_other') {
this.regex = /change the regex/;
}
});
}
Hope it help you, or other devs! :)
In you component, simply define a member variable like this:
export class AppComponent {
customPattern = '[1-9][0-9]';
In your html, use interpolation like this:
pattern = "{{customPattern}}"
That should work.

Ember-Validation Issue w/ Ember CLI & Ember Data

I'm attempting to implement form validation on a new Contact in my app using the ember-validations library. I'm currently using Ember Data with fixtures, and I've opted to place the validations in the model like the example in this video. I've been grappling with this for days now, and still can't seem to figure out why the validations aren't working. I'm not getting any indication that errors are even firing.
//app/models/contact.js
import DS from "ember-data";
import EmberValidations from 'ember-validations';
//define the Contact model
var Contact = DS.Model.extend(EmberValidations, {
firstName: DS.attr('string'),
lastName: DS.attr('string'),
});
//Create Contact fixtures
Contact.reopenClass({
FIXTURES: [...]
});
Contact.reopen({
validations: {
firstName: {
presence: true,
length: { minimum: 2 }
},
lastName: {
presence: true
}
}
});
export default Contact;
I'm new to Ember, and have been advised to put the following logic in routes instead of the controller. I haven't seen any examples of this being done with ember-validations, so I'm unsure if that's my issue regarding validations.
app/routes/contacts/new.js
import Ember from 'ember';
export default Ember.Route.extend({
model: function() {
return this.store.createRecord('contact');
},
actions: {
createContact: function() {
var contact = this.get('currentModel');
this.transitionTo('contacts');
contact.save();
alert(contact.errors);
},
cancelContact: function() {
var contact = this.get('currentModel');
contact.destroyRecord();
this.transitionTo('contacts');
}
}
});
My other suspicion is that I may not be handling the errors in html correctly?
//app/templates/contacts/new.hbs
{{#link-to 'contacts' class="btn btn-primary"}}Contacts{{/link-to}}
<form>
<label>First Name:</label>
{{input type="text" value=model.firstName}}<br>
<span class="error"></span>
<label>Last Name:</label>
{{input type="text" value=model.lastName}}<br>
<span class="error"></span>
</form>
<button {{action "createContact"}} class="btn btn-primary">Submit</button>
<button {{action "cancelContact"}} class="btn btn-warning">Cancel</button>
<br>
Here is my controller
//app/controllers/contacts.js
import Ember from "ember";
export default Ember.Controller.extend({
});
I'm enjoying Ember, but this issue is stonewalling me greatly. Any help would be much appreciated.
I'm going through this exact thing and have some advice. First I would say validate where you need to ask something if it is valid. You might need to do this on the component if it's a form, you might need to do this on a model if you want to ensure it's valid before saving, or maybe on a route if there are properties there that you're wanting to check.
In any case whatever method you pick, I would highly recommend using the ember-cp-validations addon. For what it's worth, Stephen Penner (ember.js core team) has contributed to the addon, too. It's all ready for Ember CLI as well.
The setup is actually very similar to what you're doing, but instead of reopening the class, you would define with it a mixin (example from their docs). To create the mixin that's used they have a factory called buildValidations. The nice thing is that you can use this on any Ember object.
Once you've defined your validation and mixed it into the create of your object, ie: Ember.Object.create(Validations, {}); where Validations is the mixin you've created just above (like in the docs). You are all set.
Within scope of that object you now have a validations property on the object, so something like:
var Validations = buildValidations({
greeting: validator('presence', true)
});
export default Ember.Object.create(Validations, {
greeting: 'Hello World',
actions: {
announce: function() {
alert('The current validation is: ' + this.get('validations.isValid'));
// per property validation is at:
alert('The individual validation is: ' + this.get('validations.attrs.greeting.isValid'));
}
}
})
Handlebars:
Looks like the form is {{ validations.isValid }}.
You can also <a {{action announce}}>announce the validation</a>.
Also, take a look at all the docs, there are is even more properties and use cases that this addon takes care of, including handlebars helpers, ajax/async resolution of validation, and some validators to use. If you don't find the one you're after make a function validator. Using the function validator all over, easy, make it re-usable with ember generate validator unique-username.
Hope this gets you off in the right start. This is a relatively new project but has decent support and responses on the issues has been quick.
Should also mention that because these validations are based on computed properties they work in an "Ember way" that should work great, including your models.

AngularJS: Is there any way to determine which fields are making a form invalid?

I have the following code in an AngularJS application, inside of a controller,
which is called from an ng-submit function, which belongs to a form with name profileForm:
$scope.updateProfile = function() {
if($scope.profileForm.$invalid) {
//error handling..
}
//etc.
};
Inside of this function, is there any way to figure out which fields are causing the entire form to be called invalid?
Each input name's validation information is exposed as property in form's name in scope.
HTML
<form name="someForm" action="/">
<input name="username" required />
<input name="password" type="password" required />
</form>
JS
$scope.someForm.username.$valid
// > false
$scope.someForm.password.$error
// > { required: true }
The exposed properties are $pristine, $dirty, $valid, $invalid, $error.
If you want to iterate over the errors for some reason:
$scope.someForm.$error
// > { required: [{$name: "username", $error: true /*...*/},
// {$name: "password", /*..*/}] }
Each rule in error will be exposed in $error.
Here is a plunkr to play with http://plnkr.co/edit/zCircDauLfeMcMUSnYaO?p=preview
For checking which field of form is invalid
console.log($scope.FORM_NAME.$error.required);
this will output the array of invalid fields of the form
If you want to see which fields are messing up with your validation and you have jQuery to help you, just search for the "ng-invalid" class on the javascript console.
$('.ng-invalid');
It will list all DOM elements which failed validation for any reason.
You can loop through form.$error.pattern.
$scope.updateProfile = function() {
var error = $scope.profileForm.$error;
angular.forEach(error.pattern, function(field){
if(field.$invalid){
var fieldName = field.$name;
....
}
});
}
I wanted to display all the errors in the disabled Save button tooltip, so the user will know why is disable instead of scrolling up and down the long form.
Note: remember to add name property to the fields in your form
if (frm) {
disable = frm.$invalid;
if (frm.$invalid && frm.$error && frm.$error.required) {
frm.$error.required.forEach(function (error) {
disableArray.push(error.$name + ' is required');
});
}
}
if (disableArray.length > 0) {
vm.disableMessage = disableArray.toString();
}
For my application i display error like this:
<ul ng-repeat="errs in myForm.$error">
<li ng-repeat="err in errs">{{err.$name}}</li></ul>
if you want to see everything, just user 'err' that will display something like this:
"$validators": {},
"$asyncValidators": {},
"$parsers": [],
"$formatters": [],
"$viewChangeListeners": [],
"$untouched": true,
"$touched": false,
"$pristine": true,
"$dirty": false,
"$valid": false,
"$invalid": true,
"$error": { "required": true },
"$name": "errorfieldName",
"$options": {}
Not this well formatted, but you will see these things there...
When any field is invalid, if you try to get its value, it will be undefined.
Lets say you have a text input attached to $scope.mynum that is valid only when you type numbers, and you have typed ABC on it.
If you try to get the value of $scope.mynum, it would be undefined; it wouldn't return the ABC.
(Probably you know all this, but anyway)
So, I would use an array that have all the elements that need validation that I have added to the scope and use a filter (with underscore.js for example) to check which ones return as typeof undefined.
And those would be the fields causing the invalid state.
If you want to find field(s) which invalidates form on UI without programmatically, just right click inspect (open developer tools in elements view) then search for ng-invalid with ctrl+f inside this tab. Then for each field you find ng-invalid class for, you can check if field is not given any value while it is required, or other rules it may violate (invalid email format, out of range / max / min definition, etc.). This is the easiest way.

Validating a text input to use only lower cases and numbers 0 to 9 when a link is clicked

I am making a simple web app that reads short URLs from a specific domain and then opens the short URL in the existing Internet browser. The functionality is already working but I am a bit confused on how to move forward in adding input validations to make the system more self service. I would like to validate a text input field which is not using a form. I want the text field to support only small case and numbers 0 to 9. I've found some solutions here in forum but I am not capable of fully integrating the offered solutions because most of them use forms and my programming skill is beginner's level. My input field uses the link anchor and looks like this:
<input type="text" id="keyword" placeholder="Small letters only" />
<a class="btn" href="http://mysite.com" id="domain"></a>
I need to add the following functions in my jquery script:
When the link is clicked, the script will check if the character string provided in "keyword" are lowercase and numbers only. if user inputs a character other than lowercase letters and numbers, alert message pops up "Invalid character detected. Try again".
If no input was provided when the link is clicked, alert message pops up "Provide an input." .
When the input is valid, the script below is run.
Thank you for your assistance.
$(function()
{
$('#domain').click( function()
{
window.location = $(this).attr('href') + '/' + $('#keyword').val();
return false;
}
});
});
You can use Regular Expressions for this validation.
$(function {
$('#domain').click( function() {
var val = $('#keyword').val();
if (val == '') { /* popup time */ }
var regexp = new RegExp("[a-z0-9]+");
if (regexp.match(val)) { /* Redirect */ }
else { /* invalid characters */ }
})
});

Jquery validation plugin dynamically add rules if control exists

I am adding a whole bunch of Jquery validation rules dynamically. I am getting error because some of the textboxes are hidden based on user selection on the page before and therefore do not exist on the page. How do I check if the textbox exists before adding the validation rules?
Here are the validation rules being added:
$('[id$="txtLastName"]').rules('add', {
isSpecialChar: true,
maxlength: 13,
oneOrBothEntered: "txtFacility",
messages: {
oneOrBothEntered: "Either Provider Name or Facility Name must be entered"
}
});
$('[id$="txtFirstName"]').rules('add', {
isSpecialChar: true,
maxlength: 11,
conditionallyRequired: "txtLastName",
messages: {
conditionallyRequired: "This field is required."
}
});
...and a whole bunch more. So say txtLastName was hidden, this code breaks. How do I check first if txtlastname exists before adding the rules?
EDIT:
Per #sparky's comment, adding HTML for fields:
<div class="container1">
<span class="span150Padded">Last</span>
<asp:TextBox ID="txtLastName" runat="server" CssClass="textBoxMedium"></asp:TextBox>
</div>
<div class="container1">
<span class="span150Padded">First</span>
<asp:TextBox ID="txtFirstName" runat="server" CssClass="textBoxMedium"></asp:TextBox>
</div>
The reason I am adding the rules dynamically is because I am using master pages so my fields are renamed. I couldn't use the <%=textbox.ClientID%> method because my validation is in a separate js file which is referenced and called from my aspx page, and a js file won't recongnize something like that. After alot of back and forth, I have found that the cleanest solution was to add the validation rules dynamically.
If you have another suggestion for me, please let me know.
When using the jQuery Validate plugin or any of its methods, the plugin will not target all elements if your selector targets more than one element.
Use the jQuery .each() method to target all elements.
$('[id$="txtLastName"]').each(function() {
$(this).rules('add', {
...
});
});
EDIT:
If you want to avoid using .each(), then target the one element.
$('#justOneField').rules('add', {
...
});
Per the documentation
$("#myform").validate({
ignore: ":hidden"
});

Resources