How to validate form when user clicks elsewhere - html

For the sign up form I am making, I want to validate passwords so that a user must enter a password that includes at least one capital letter and at least one number.
I have implemented this here:
http://jsfiddle.net/k9aHV/1/
<form action="login.php" method="post">
<p><b>UserName:</b> <input type="text" required pattern="\w+" name="fname"/></p>
<p><b>Password:</b> <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" name="password" onblur="this.setCustomValidity(this.validity.patternMismatch ? 'Password must contain at least 6 characters, including UPPER/lowercase and numbers' : '');if(this.checkValidity()) form.password1.pattern = this.value;"></p>
<p><b>Confirm Password:</b> <input type="password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" name="password1" onblur="
this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same password as above' : '');"/></p>
<p><b>Email:</b> <input type="email" name="email"/></p>
<input type="submit"/>
</form>
At the moment, the field is validated only when the user presses submit.
How can I adjust my code so that the code is validated as soon as the user tabs or clicks away from the input field?

You can trigger native validation on blur like so
input.addEventListener('blur', function(e) {
e.target.checkValidity();
});
The problem is you can't trigger the validation error popup programmatically.
One workaround is to programmatically click the submit button BUT the popup will only show the first invalid input element!
A more user friendly solution is to show the validation message in an element.
See this JSFiddle
var idx;
var passwordInputs = document.querySelectorAll('input[type="password"]');
for(idx=0; idx< passwordInputs.length; idx++) {
//set custom validation
passwordInputs[idx].addEventListener('input', function(e) {
if(e.target.validity.patternMismatch) {
e.target.setCustomValidity('Password must contain at least 6 characters, including UPPER/lowercase and numbers');
}
else {
e.target.setCustomValidity('');
}
});
}
//code starting here is to show the validation message in a span element
function showValMessage(elem, msg) {
var span = elem.parentNode.querySelector('span');
span.innerText = msg;
}
var inputs = document.querySelectorAll('input');
for(idx=0; idx< inputs.length; idx++) {
var input = inputs[idx];
//validate on blur
input.addEventListener('blur', function(e) {
e.target.checkValidity();
});
//show validation message
input.addEventListener('invalid', function(e) {
showValMessage(e.target, e.target.validationMessage);
});
//hide validation message. There is on valid event :(
input.addEventListener('input', function(e) {
if(e.target.validity.valid) {
showValMessage(e.target, '');
}
});
}

Related

Jquery validate error messages not showing up

i have an array of inputs generated upon a press of a button. the index is maintained using a global variable numInput set to 0. This is the first HTML of the input.
<label><span>First name</span>
<input placeholder="First name" type="text" name="fName[0]" id="fName"></label>
This is the addmore button, which increments numInput and appends the new and mostly the same HMTL with different index
$(document).on('click','#addmore',function(){
numInput++;
var html = '<label><span>First name</span>
<input placeholder="First name" type="text" name="fName['+numInput+']" id="fName"></label>';
$("#frm").append(html);
rerunRules();
});
Here is my validate method. I did not create the message object here...
$(document).ready(function() {
$('#frm').validate({
highlight: function(element, errorClass) {
$(element).fadeOut(function() {
$(element).fadeIn();
});
},
errorPlacement: function(error, element) {
error.appendTo(element.prev("span"));
},
});
});
rerunRules();
instead I changed the defaults:
<script>
jQuery.extend(jQuery.validator.messages, {
required: "- This field is required."
});
</script>
The rerunRules() is a function that I had to call to "reinject" the rules everytime a new HTML is generated. It is also called right after validate() because the fName rules are in it.
function rerunRules(){
$.each( $('input[name^="fName"]'), function () {
$(this).rules('add', {
required: true
})
});
}
Contrary to what I expected, the error message appears on the first fName[0] just as where its meant to be (to the previous span) but doesnt appear on the next generated HTML from the button. The validate works (wont proceed when I dont enter proper data), the highlight works, but no error message.

how frequently pattern attribute will be validating the text entered in html input

when i am doing a input field validation using pattern , how frequently the value will be validated . i would like to know whether it will validate on (keyup) or (change)
for ex:
<input type="email" [(ngModel)]="emailAddress" name="emailAddress" data-toggle="tooltip"
title="{{emailAddress}}" #email="ngModel" multiple
pattern="^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$"
class="form-control" />
i would like to know whether the text i enter will be validated on each keystroke ?
The pattern attribute is checked only upon submission the form or when you press enter on the input tag, so only on the enter key's stroke you might say.
If you want it to be validated on every keypress, keyup or onchange, you can set the corresponding attribute to validate the input like so:
<input keyup="validate(this)" />
...
<script>
function validate(x)
{
regex = /[a-zA-Z0-9]+/;
window.alert(x.value.match(regex) == null);
}
</script>
If I understand correctly your issue, you are trying to check the value entered "real time".
In the case, you could use input event to get value changed.
// Add error message element after input.
$('#input_email').after('<span class="error-message">Please write your message error here!</span>')
$('#input_email').on('input', function (evt) {
var $regex=/^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$/;
var value = evt.target.value;
if (value.length === 0) {
evt.target.className = ''
return
}
var result = value.match($regex);
if (result) {
evt.target.className = 'valid'
} else {
evt.target.className = 'invalid'
}
})
input.invalid + .error-message {
display: initial;
}
.error-message {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input_email" type="email" [(ngModel)]="emailAddress" name="emailAddress" data-toggle="tooltip"
title="{{emailAddress}}" #email="ngModel" multiple
pattern="^(([a-zA-Z0-9_,.]*#*\w+([-+.']\w+)*\w+([-.]\w+)*\.\w+([-.]\w+)*)*([' '])*)*$"
class="form-control" />

How to block entering gmail adress in textbox or show popup?

I need a textbox in my form for entering email address.But address should be business email.Never allow to enter personal gmail or yahoo address or show warning popup while doing so.How to implement that?Can i use angulars ng-pattern to implement it?
You can do something like this. No need for angular pattern.
HTML
<form id="signup" method="post">
<input id="email" type="email" placeholder="Your e-mail." />
</form>
JS
$('#email').blur(function() {
validateEmail($('input').val());
return false;
});
function validateEmail(email) {
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(email)) {
if (email.indexOf('#yourdomain.com', email.length - '#yourdomain.com'.length) !== -1) {
alert('Valid email.');
} else {
alert('Email must be a yourdomain e-mail address (your.name#yourdomain.com).');
}
} else {
alert('Not a valid e-mail address.');
}
}
Check the fiddle
Reference

javascript/jQuery Double Submit Prevention method disables initiation of html5 attributes (e.g. Required, Pattern, etc.)

The javascript/jQuery double submit prevention method I use is this:
$("#btnsubmit").click(function () {
$("#btnsubmit").attr('disabled','disabled');
$('#postform').submit();
});
So on submit click, the Submit Button is disabled and the form is submit. So double submit of the form will not happen. BUT. The problem now is that the html5 attributes will not initiate (e.g. Required, Pattern, etc.)
Does anyone have any ideas on how to fix this?
or maybe you can suggest alternative double submit prevention method that will not tamper with the html5 attributes?
EDIT + DANIEL PATZ ANSWER:
$('#postform').on('submit', function (e) {
// THIS PART
var titleLength = $("#title").val().length;
var descriptionLength = $("#description").val().length;
if(titleLength < 20 || descriptionLength < 150) {
$("#ps").text("Title and Desc Problem.");
} else {
// UNTIL HERE
$('[type="submit"]').prop('disabled','disabled');
}
});
If you catch the submit event, it should work. http://jsfiddle.net/tcc7u/
HTML:
<form>
<input required /><br />
<input type="submit" />
</form>
JS:
$('form').on('submit', function (e) {
$('[type="submit"]').prop('disabled','disabled');
});

How to present asterisk when entering a password in index.html

Using that code :
<!-- THIS IS WHERE IT ALL STARTS -->
<!DOCTYPE html>
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Web Bank application</th></tr>
</table>
<br/>
<fieldset>
<legend>Login Page - please enter your Username and Password</legend>
<form action="loginPage">
Username: <input type="text" name="username"><br>
Password : <input type="text" name="password"><br>
<input type="submit" value="Login">
</form>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/><br/><br/><br/><br/><br/>
</body></html>
The user enters his username and password
How can I present to the screen asterisks (*) when I enter the password , e.g. instead of showning myPassword , I want to present ********** , and keep the actual characters of the string myPassword in tact ?
Thanks
<input type="password" name="password">
change it to
<input type="PASSWORD" name="password">
Specifications
Control types created with INPUT
When working with passwords, use the input type="password" instead of text.
The format is the same, it will just tell the browser that you want your user to enter a password in it, or other sensitive data, that should be hidden from weary eyes. So the browser will not show the typed characters (or just briefly), but will show asterisks instead.
Username: <input type="text" name="username"><br>
Password : <input type="password" name="password"><br>
Right, #eric-yin has the correct answer: An input with type="password" masks the password.
Nevertheless, Like #beefchimi, i needed: a password field that can:
Show asterisks in every browser
Show the final character without an asterisk
So i wrote this jQuery plugin:
$.fn.betta_pw_fld = function(pwfld_sel, hiddenfld_sel) {
// this is the form the plugin is called on
$(this).each(function() {
// the plugin accepts the css selector of the pw field (pwfld_sel)
var pwfld = $(this).find(pwfld_sel);
// on keyup, do the masking visually while filling a field for actual use
pwfld.off('keyup.betta_pw_fld');
pwfld.on('keyup.betta_pw_fld', function() {
// if they haven't typed anything...just stop working
var pchars = $(this).val();
if (pchars == '') return;
// we'll need the hidden characters too (for backspace and form submission)
var hiddenfld = $(this).parents('form').find(hiddenfld_sel);
var hchars = hiddenfld.val();
// use these placeholders to build our password values
// this one will have all asterisks except the last char
var newval = '';
// this one will have the actual pw in it, but we'll hide it
var newhpw = '';
// in this block, we're in a "keydown" event...
// let's get the characters entered
// loop over them and build newval and newhpw appropriately
for (i=0; i<pchars.length - 1; i++) {
if (pchars[i] == '*') {
newhpw += hchars[i];
} else {
newhpw += pchars[i];
}
newval += '*';
}
// we want to see the last character...
var lastchar = pchars[pchars.length - 1];
if (lastchar == '*') {
newval += hchars[pchars.length - 1];
newhpw += hchars[pchars.length - 1];
} else {
newval += pchars[pchars.length - 1];
newhpw += pchars[pchars.length - 1];
}
// set the updated (masked), visual pw field
$(this).val(newval);
// keep the pw hidden and ready for form submission in a hidden input
hiddenfld.val(newhpw);
});
});
};
The html might be:
<form id="myForm">
<label for="pw">Type password:</label><br>
<input name="pw" class="stylishPassword" type="text"><br>
<input class="hiddenPassword" type="hidden">
</form>
And at document.ready, or appropriate time, the plugin is instantiated like this:
$('#myForm').betta_pw_fld('.stylishPassword', '.hiddenPassword')
Visit the Better Password Field jQuery Plugin Codepen and then please remember to vote it up if it helps you.