How to validate password from asp.net in js? - javascript

I have this input:
aspx
<input type="password" id="password" name="password" data-fv-stringlength-min="5" class="form-control col-md-7 col-xs-12" required="required" pattern="password" title="Follow the password requirement"/>
js
if( pattern ){
var regex, jsRegex;
switch( pattern ){
case 'alphanumeric' :
regex = /^[a-zA-Z0-9]+$/i;
break;
case 'numeric' :
regex = /^[0-9]+$/i;
break;
case 'phone' :
regex = /^\+?([0-9]|[-|' '])+$/i;
break;
case 'password':
regex = /^(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "])+$/i;
break;
}
}
the password case doesn't works fine. when I click on the password field and type any letter, it stuck and I can't enter any letter !
edit
in aspx, i use the following script:
<!-- validator -->
<script>
// initialize the validator function
validator.message.date = 'not a real date';
// validate a field on "blur" event, a 'select' on 'change' event & a '.reuired' classed multifield on 'keyup':
$('form')
.on('blur', 'input[required], input.optional, select.required', validator.checkField)
.on('change', 'select.required', validator.checkField)
.on('keypress', 'input[required][pattern]', validator.keypress);
$('.multi.required').on('keyup blur', 'input', function() {
validator.checkField.apply($(this).siblings().last()[0]);
});
//$('#add_member_form').formValidation();
$('form').submit(function(e) {
e.preventDefault();
var submit = true;
// evaluate the form using generic validaing
if (!validator.checkAll($(this))) {
submit = false;
}
if (submit)
this.submit();
return false;
});
</script>
<!-- /validator -->
Note:
I am using free bootstrap template. therefore, all the code is written in the template and I try to edit it to suite my need and try to understand it.
Edit2 : pattern code is in validator.js "coming with the template"
var validator = (function($){
var message, tests;
message = {
invalid : 'invalid input',
email : 'email address is invalid',
tests = {
email : function(a){
if ( !email_filter.test( a ) || a.match( email_illegalChars ) ){
alertTxt = a ? message.email : message.empty;
return false;
}
return true;
},
text: function (a, skip) {
if( pattern ){ // pattern code },
number : function(a){ // number code // },
date : function(a){ // date code // },

Your issue is not clear, and need more details
First, choose a method
Actually, you have two options to get what you want to do.
HTML5, using a pattern attribute
Many input types are able to manage their own pattern
(like email, phone, password...)
You must specify the pattern into the attribute "pattern",
without delimiters /.../ (and options)
<input
type="password"
id="password"
name="password"
data-fv-stringlength-min="5"
class="form-control col-md-7 col-xs-12"
required="required"
pattern="^(?=.{8,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? \"])+$"
title="Follow the password requirement"/>
But be careful with escaping quotes that can collide with the attribute quotes
JS, from a control javascript
Since i don't understand what are ou doing with your 'incomplete' code (above in you post).
I suppose, you have defined some onKeyDown events on inputs to catch when user is writing and calling the actual code under a function ?
I don't see the required condition to match the inputs values !
Can you update your post with more details, and i'll update mine too.
If you choose to continue with you plugin
Okay, in concerne of your edit2, using i guess jquery.form.validator:
var validator = (function($){
var message, tests;
message =
{
invalid : 'invalid input',
email : 'email address is invalid',
};
tests =
{
// <input type="email">
email : function(a)
{
if( !email_filter.test( a ) || a.match( email_illegalChars ) )
{
alertTxt = a ? message.email : message.empty;
return false;
}
return true;
},
// this is for <input type="text">
text: function (a, skip)
{
if( pattern ){ // pattern code },
},
// this is for <input type="number">
number : function(a){ /* number code */ },
date : function(a){ /* date code */ },
};
Then, i think you have to add you password method to tests:
// this is for <input type="password">
password: function (a, skip)
{
if( pattern ){ /* pattern code */},
},
Or i propose to you, a more simple
And not plugin requiring solution, by reusing your original code
from your (first duplicate post) How to validate password field in bootstrap?
note: stop using removeClass(...).addClass(...), would prefer
short and relevant methods like toggleClass(classname, condition)
or switchClass(classbefore, classafter)
CSS
.invalid { color: red!important; } /* note this important flag is require to overwrite the .valid class */
.valid { color: lime; }
HTML hint
<div id="pswd_info">
<h4>Password requirements:</h4>
<ul>
<li id="letter" class="fa-warning"> At least <strong>one letter</strong></li>
<li id="capital"> At least <strong>one capital letter</strong></li>
<li id="number"> At least <strong>one number</strong></li>
<li id="special"> At least <strong>one special character</strong></li>
<li id="length"> Be at least <strong>8 characters</strong></li>
<li id="password"> Must contains at least <strong>8 characters</strong>, specials chars (#$!...) and numbers</li>
</ul>
</div>
</div>
Jquery
$("form input").on("keyup", function(event)
{
var invalidClass = "invalid";
var type = $(this).attr("type");
var val = $(this).val();
switch(type)
{
case "email": /* */ break;
case "phone": /* */ break;
case "number":
{
var smt = (/^\d$/i.test(val);
$('#number').toggleClass(invalidClass, smt);
break;
}
case "password":
{
var smt = (/^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,16}$/i.test(val);
$('#password').toggleClass(invalidClass, smt);
break;
}
}
}).on("focus", function()
{
$('#pswd_info').show();
}).on("blur", function()
{
$('#pswd_info').hide();
});

Related

Using QUnit to test if item has a certain class

I've created a password input module which has a couple of regexes and a list underneath telling the user which requirements to meet in order to create the password, aka submit the form. I'm adding/removing a class to each requirement list item on keyup depending on if it meets the requirement or not.
I'm using QUnit to test if these elements gets the class or not. Any ideas?
Codepen:
http://codepen.io/eplehans/pen/xVYMLp
HTML looks roughly like this:
<label for="password">Password input</label>
<input pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[a-z]).*$" id="password" name="password" type="password">
<ul class="input-requirements-list">
<li class="input-requirements-list__item" data-psw-req="8-chars">8 characters minimum</li>
<li class="input-requirements-list__item" data-psw-req="1-special-char">1 special character</li>
</ul>`
JS looks roughly like this:
function passwordRegEx($input, $list) {
var currentVal;
var affirmativeClass = 'affirmative';
function okCheck($el, affirmative) {
if (affirmative === true) {
$el.addClass(affirmativeClass);
} else {
$el.removeClass(affirmativeClass);
}
}
//Requirements as shown in requirements list underneath password input
var $charChecker = $list.find('[data-psw-req="8-chars"]'),
$specialCharChecker = $list.find('[data-psw-req="1-special-char"]');
$input.keyup(function() {
currentVal = $input.val();
//More than 8 characters
if (currentVal.length >= 8) {
okCheck($charChecker, true);
} else {
okCheck($charChecker, false);
}
//Special character match
if (currentVal.match(/[-!$%^&*()#øæåØÆÅ_+|~=`{}\[\]:";'<>?,.\/]/)) {
okCheck($specialCharChecker, true);
} else {
okCheck($specialCharChecker, false);
}
});
}
QUnit test looks like this:
var $passwordInput = $('#password'),
affirmativeClass = 'affirmative';
var $reqItem1 = $('li[data-psw-req="8-chars"]'),
reqItem2 = $('li[data-psw-req="1-special-char]');
QUnit.test("Expect [data-psw-req=8-chars] to have class when requirements are met", function(assert) {
$passwordInput.val('123456789dddddd');
ok($reqItem1.hasClass(affirmativeClass), true, "It has the class!");
});
You must trigger the same event like the one the user trigger when is writing. Here I trigger the keyup event, just like a user does when he is finishing the typing.
http://codepen.io/tomkarachristos/pen/MyQxbQ
QUnit.test("Expect li[data-psw-req=8-chars] to have affirmative class when password input has 8 or more characters", function(assert) {
$passwordInput.val('123456789dddddd');
$passwordInput.keyup();
ok($reqItem1.hasClass(affirmativeClass), true, "It has the class!");
});

Problems with validate jquery function

I was trying to make a validation in my form with jquery, but it does not work the way it was supposed to and I have no idea why.
I have this function to make the validation:
function newLogin () {
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
if (username == "" || password.length<5){
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
});
return false;
}
else{
Parse.User.logIn(username, password, {
success:function(user){
console.log("login successfull");
if(checkEmail()){
console.log(checkEmail());
document.location.href = "Temas.html";
}
},
error: function(user, error){
console.log(error.message);
displayErrorDiv();
}
})
}
}
And i got this form
<form id = "popup-login-form">
<input type="email" name="email" placeholder="Email" id = "popup-login-email" class="popup-input first"/>
<div id="error-message-email" class="error">
</div>
<input type="password" name="password" placeholder = "Password" id="popup-login-password" class="popup-input"/>
<div id="error-message-password" class="error">
</div>
<button class="popup-button" id="popup-cancel">Cancel</button>
<button type="submit" class="popup-button" id="popup-submit">Login</button>
<div class="error-message-login" class="error">
</div>
</form>
And the weird part is that just does not work in my page. Here it works, for example: http://jsfiddle.net/xs5vrrso/
There is no problem with the code which you shared in jsfiddle but the above code you are using $(document).ready({function()}) inside a function which is of no use. Now the problem is that the method newLogin is not called on dom ready and thus this issue occurs.
Better keep the function call inside $(document).ready({function() newLogin() }) . Now you can also use submitHandler in validate to merge the if else conditions.
i make one example to you
jsfiddler example
$(document).ready(function () {
$("#popup-login-form").validate({ // initialize the plugin
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
});
//event listening onSubmit
$('form').submit(function(event){
var returnForm = true;
var username = $("#popup-login-email").val();
var password = $("#popup-login-password").val();
//Make your validation here
if (username == "" || password.length<5){
returnForm = false;
}
return returnForm; //Submit if variable is true
});
});
With jQuery when i get the
"TypeError: $(...).validate is not a function"
I change
$(..).validate
for
jQuery(..).validate
You have to include this validate file after jquery file.
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.js"></script>
Do not wrap the code under the if condition with $(document).ready(). Change the code to :
if (username == "" || password.length < 5){
$("#popup-login-form").validate({ // initialize the plugin
/*remaining code here*/
});
}
Also it is a good habit to trim the spaces around any input that you accept from the users. For e.g in your case please do the following:
var username = $.trim($("#popup-login-email").val());
var password = $.trim($("#popup-login-password").val());
/* $.trim() would remove the whitespace from the beginning and end of a string.*/

Want to validate the user on a button click for ipaddress field using jquery input mask plugin

I am using jquery mask plugin https://igorescobar.github.io/jQuery-Mask-Plugin/
i want to validate the field ipaddress if the user enter 192.3.4. and forgot to put value after . then i want to validate the text input box then when the user click on the save button
Here is my Html
<input type="text" class="form-control ip_address" placeholder="*IP Address">
and here is my jquery for the plugin mask
$('.ip_address').mask('0ZZ.0ZZ.0ZZ.0ZZ', {
translation: {
'Z': {
pattern: /[0-9]/, optional: true
}
}
});
and here is how i want to validate the user on burron click
$('.btnsaveForm').on('click', function(e) {
e.preventDefault();
var ip = $('.ip_address').val();
if(ip){
alert('ip address');
}else{
alert('not an ip address');
}
});
Kindly help me Thanks
You may try a RegExp as below.
$('.btnsaveForm').on('click', function(e) {
e.preventDefault();
var ip = $('.ip_address').val();
if(/^\d+\.\d+\.\d+\.\d+$/.test(ip)) {
alert('valid ip address');
}else{
alert('not an ip address');
}
});
\d+ => match numbers only
\. => match a .
^ => input start point
$ => input end point
Edit: You may write a basic plugin like below.
(function ( $ ) {
$.fn.isIpv4 = function() {
return /^\d+\.\d+\.\d+\.\d+$/.test( $(this).val() );
};
}( jQuery ));
Use it as:
var ip = $('.ip_address'); // no val() here!
if( ip.isIpv4() ) {
alert('valid ip address');
}
Edit: As per your last comment, you would be better off using a function like below as a jQuery plugin is not meant for this.
function isIpv4(ip) {
return /^\d+\.\d+\.\d+\.\d+$/.test(ip);
}
var ipAdd = $('.ip_address').val();
if( isIpv4(ipAdd) ) {
alert('valid ip address');
}

JavaScript script to validate minimum words entered in input

I really don't know how to do this. So I need a JavaScript script that'd look at the contact form field (question name) and make sure it has more than one word before submitting it.
<input type="text" name="question[name]" id="question_name">
I really searched a lot, found some solutions but non of them really worked.
Can you help me?
Here a fiddle http://jsfiddle.net/6q8jJ/4/
html
<input type="text" name="question[name]" id="question_name">
<button onclick="validate();">send</button>
js
function validate(){
var error = 0,
el = document.getElementById("question_name");
if(el.value.replace(/\s+/g, '').length <= 1){ //get value, remove all whitespace, get length
error++;
}
/*
* etc
* your other validation
*/
if(error > 0) {
alert('mhh...');
}else{
alert('ok send for real');
}
}
<input type="text" name="question[name]" id="question_name" onblur="this.value.split(' ').length < 2 ? alert('you need more words here') : '';" />
jsfiddle
Edit to improve it:
HTML code:
<p>
<input type="text" name="question[name]" id="question_name" onblur="CheckErrors.Name(this);" />
<span class="error"></span>
</p>
JS code:
var CheckErrors = {
Config: {
Error_Strings: {
Name: 'you need more words here',
Email: 'the email looks invalid'
//, ....
}
},
Name: function(element){
try{
var error_target = element.nextElementSibling;
if( element.value.split(' ').length < 2 ){
error_target.textContent = this.Config.Error_Strings.Name;
}
else{
error_target.textContent = '';
}
}
catch(e){
console.log(e.stack);
}
}
//, Email: function(element){}....
};

Alerts conditional on model validation

I have an Picture model with various validations:
validates :title, presence: true
validates :caption, presence: true
validates :image, presence: true
validates :price, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 1000 }
validates_size_of :tag_list, :minimum => 3, :message => "please add at least three tags"
The tag list has to be submitted in a specific format: at least three tags, separated by a comma and a space: eg foo, bar, cats
I want to have an alert that tells the user to "please wait, we're uploading your image" - but only AFTER the model has passed ALL of the validations ( before the .save in the controller)
Is there a way of doing this in the controller, which I'd prefer, or do I have to use some javascript like:
$("form#new_picture").on("submit", function () {
if LOTS OF HORRIBLE REGEX ON FORM FIELDS {
MESSAGE HERE
return true;
} else {
return false;
}
});
OR Is there a way of doing this in the model, as part of an after_validation callback?
Any suggestions much appreciated. Thanks in advance.
I would build a JS function to extract the fields that I want to be validated.
Then create a custom AJAX controller action, which:
instantiates a new object with given params
call valid? on it without saving it
Then:
On failure, update the form with error messages
On success, I would return a custom ajax response to display the alert and start POSTing the real object.
I've realised that this isn't really possible through through the model or controller, and resorted to a combination of three validation processes:
Validations in the model
The simpleform client side validations gem - this is v good, it tests validity the moment a form field loses focus - "real time" validation.
And some additional javascript to alert with popups and errors, pasted below.
Hopefully this makes the form virtually un-submittable without the user knowing what's missing.
THE JS SOLUTION
FORM
<form id="new_pic" novalidate>
<p><input type="file" name="file" required></p>
<p><input type="string" name="name" placeholder="Name" required></p>
<p><input type="string" name="tags" placeholder="Tags" data-validation="validateTags"></textarea></p>
<p><textarea name="description" data-validation="validateDescription"></textarea></p>
<p><button type="submit">Submit</button>
</form>
JS
var Validator = function(form) {
this.form = $(form);
}
$.extend(Validator.prototype, {
valid: function() {
var self = this;
this.errors = {};
this.form.find('[required]').each(function() {
self.validateRequired($(this));
});
this.form.find('[data-validation]').each(function() {
var el = $(this),
method = el.data('validation');
self[method].call(self, el);
});
return $.isEmptyObject(this.errors);
},
validateRequired: function(input) {
if (input.val() === '') {
this.addError(input, 'is required');
}
},
validateDescription: function(input) {
if (input.val().length < 64) {
this.addError(input, 'must be at least 64 characters');
}
},
validateTags: function(input) {
var tags = input.val().split(/, ?/);
if (tags.length < 3) {
this.addError(input, 'must have at least 3 tags');
}
},
addError: function(input, error) {
var name = input.attr('name');
this.errors[name] = this.errors[name] || [];
this.errors[name].push(error);
input.after('<span class="error">' + error + '</span>');
}
});
$('form#new_pic').on('submit', function(event) {
event.preventDefault();
var form = $(this),
validator = new Validator(form);
form.find('.error').remove();
if (validator.valid()) {
// continue with upload
alert('Go!');
return true;
} else {
// complain
alert('Stop!');
return false;
}
});

Categories