Onfocusout problems - javascript

I have a JavaScript function that is triggered when the onfocusout attribute of an input field is called, which works perfectly.
The only problem I have is that at the first time, whenever the user inputs a text, after executing the JavaScript function, the value of the input disappears from the screen, so the user has to input it a second time.
How can I solve this?
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" onfocusout="passcheck(0)" title="input must not be less than 8 characters" required></input>
function passcheck(type){
var status=false;
switch(type) {
case 1:
var divP=document.getElementById("form-group password");
if(!document.getElementById("passHelp"))
divP.innerHTML+="<small id='passHelp' hidden class='form-text text-muted' color='red'>Password mismatch.</small>";
if(!status){ document.getElementById("passHelp").hidden=false;
document.getElementById("passHelp").style.color="Red";
}
else{ document.getElementById("passHelp").hidden=true; }
break;}
return status; }

Related

How to force validate data of the HTML 5 input from jquery?

I do have a input with the pattern and the title to show the error in case of wrong data, I do need to not use the post method, so I just make some Jquery code to use the input validation, but I can't find how to show the default message of the input
This is the HTML5 input:
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
And this is the jquery code:
$("#inputEnviar").click(
function(){
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if ( userValidation ){
//code to do whatever I have to do if the data is valid
} else {
//if the data is invalid
//the input already has a default message to show
//then, how do I force to show
$("#user")-> FORCE TO SHOW TO THE DEFAULT ERROR MESSAGE OF THE INPUT
}
});
If the validation fails, in your else code block, set the custom message that you want to notify to the user:
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
Then, you can use reportValidity() to show that message. From MDN:
The HTMLFormElement.reportValidity() method returns true if the element's child controls satisfy their validation constraints. When false is returned, cancelable invalid events are fired for each invalid child and validation problems are reported to the user.
$("#inputEnviar").click(
function() {
var userValidation = $("#user")[0].checkValidity();
//validate if the pattern match
if (userValidation) {
//code to do whatever I have to do if the data is valid
} else {
$("#user")[0].setCustomValidity("Please enter at least 5 characters.");
var isValid = $('#user')[0].reportValidity();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="user" pattern="whatever pattern" title="wrong value" required>
<input id="inputEnviar" type="button" value="Send">
For old browsers (i.e. IE) you would need to use a polyfill.
There are several implementations around (like this git). This article goes deeper on the topic.
This should work. The reportValidity() function will show the default message after you have set it with setCustomValidity.
function send() {
var input = $("#user")[0];
input.setCustomValidity("");
if(!input.checkValidity()) {
input.setCustomValidity("watch me break");
input.reportValidity();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="user" pattern="[^,]*" title="Message">
<button onclick="send()">Click</button>

Javascript enabling input field after disable=true

html:
<label>Label1</label><br>
<input type="text" name="first" onclick="somefunc()"><br>
<label>Label2</label><br>
<input type="text" name="second"><br>
Javascript:
function somefunc() {
var second = document.getElementsByName('second')[0];
second.disable = true;
}
When I click the first input the second is disabled (that was what I want), but when I type something into the first input field, then delete it, the second is still disabled. Is there a way so I can enable it again?
I couldn't find an other event which can solve this.
You can listen to the keyup event on the first input box and check the value of first input box for enabling or disabling second input.
<label>Label1</label><br>
<input type="text" name="first" onkeyup="somefunc()"><br>
<label>Label2</label><br>
<input type="text" name="second"><br>
<script>
function somefunc() {
var first = document.getElementsByName('first')[0];
var second = document.getElementsByName('second')[0];
if(first.value){
second.disabled = true;
}else{
second.disabled = false;
}
}
</script>
Seems you have missed enabling textbox here. If you can see in previous reply, you just need to re-enable textbox into same state as it was before.

HTML5 Form validation - error message customization

I have a form with an input like this.
<input type="text" name="question" class="form-control" required="" minlength="4" maxlength="2" size="20" oninvalid="setCustomValidity('please enter something')">
Now the default validation messages work great. But I want to set custom messages for specific rules.
i.e. for rules like required minlength maxlength when each fails I want to provide a custom error message specific to the rule that failed.
I have tried oninvalid="setCustomValidity('please enter something')" but that sets that message for every rule.
How can I specify custom error messages for specific rules?
Use setCustomValidity property to change validation messages and validity property to find type of validation error
validity : A ValidityState object describing the validity state of the element.
Upon form load validate property is initialized for each form element and updated on every validation due to user events like keypress,change etc. Here you can find the possible values
var email = document.getElementById("mail");
if (email.validity.valueMissing) {
email.setCustomValidity("Don't be shy !");
}
else{
event.target.setCustomValidity("");
}
email.addEventListener("input", function (event) {
if (email.validity.valueMissing) {
event.target.setCustomValidity("Don't be shy !");
}
else{
event.target.setCustomValidity("");
}
});
Demo https://jsfiddle.net/91kc2c9a/2/
Note: For some unknown reason email validation is not working in the above fiddle but should work fine locally
More on ValidityState here
The oninvalid event occurs when the input is invalid, in your case, the input is required and if it is empty, oninvalid will occur. (see this)
And yes, maxlength should be bigger than minlength and instead of required="" you can simply write required
if your code is like this (with an ID 'input-field'):
<input type="text" name="question" id="input-field" class="form-control" required="" minlength="4" maxlength="8" size="20" oninvalid="setCustomValidity('please enter something')">
You will need to add custom functions to check different validation and display different errors based on them.
The validator() function bellow triggers when the input box loses focus and checks for its requirements, and the valdiator_two() is triggered on every keypress in the input field:
var field = document.getElementById("input-field");
function validator(){
if (field.value === "") {
alert("You can't leave this empty");
}
if (field.value !== "" && field.value.length < 4){
alert("You have to enter at least 4 character");
}
}
function validator_two(){
if (field.value.length >= 8){
alert("You can't enter more than 8 character");
}
}
field.addEventListener("blur", validator);
field.addEventListener("input", validator_two);
<input type="text" name="question" id="input-field" class="form-control" required="" minlength="4" maxlength="8" size="20" oninvalid="setCustomValidity('please enter something')">

'onblur' event, iterating through all the fields of a form, without giving the user a chance to enter data

I am in the process of writing a contact form. I have two JavaScript functions in the head (I will move them later, but that is another question).
The first function, Validate(), for the onblur event works, but not as I'd like it to. The second function, formValidate(), for the onsubmit event works.
I have a switch statement in a JavaScript function to use in an HTML onblur event.
The JavaScript code:
<head>
<script type="text/javascript">
function Validate()
{
// Create array containing textbox elements
var input = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email1'), document.getElementById('email12'), document.getElementById('message')];
// Loop through each element to see if value is empty
for (var i = 0; i<input.length; i++)
{
if (input[i].value == '')
{
switch( input[i].id){
case 'fname':
alert ('enter you first name');
break;
case 'lname' :
alert ('enter your last name');
break;
case 'email1':
alert ('enter your email address');
break;
case 'email2':
alert ('enter your email address');
break;
case 'message':
alert ('write your message');
break;
}
}
}
}
function formValidate()
{
// Create array containing textbox elements
var inputs = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email1'), document.getElementById('email2'), document.getElementById('message')];
var error;
// Loop through each element to see if value is empty.
for(var i = 0; i<inputs.length; i++)
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
alert(error);
return false;
}
}
}
</script>
</head>
The HTML:
<form onsubmit="return formValidate()" action="mailto:admin#sfasc.com.au" method="post" id="contactForm" >
<fieldset>
<dl>
<dt> First Name:</dt>
<dd>
<input class="input" type="text" name="fname" id="fname" onblur="Validate()" />
</dd>
<dt> Last Name:</dt>
<dd>
<input class="input" type="text" name="lname" id="lname" onblur="Validate()"/>
</dd>
<dt> Email Address:</dt>
<dd>
<input class="input" type="text" name="email1" id="email1" onblur="Validate()"/>
</dd>
<dt> Email Address:</dt>
<dd>
<input class="input" type="text" name="email2" id="email2" onblur="Validate()"/>
</dd>
<dt> Message:</dt>
<dd>
<textarea name="address" id="address" rows="10" cols="10" onblur="Validate()"></textarea>
</dd>
<dd>
<input type="submit" value="submit" name="submit" />
</dd>
</dl>
</fieldset>
</form>
The code works, except for this: When I click on a field, I get the following alert:
If I click, prevent pop ups, the alerts stop entirely. If I click OK, it goes to the next field, eg from fname to lname, and continues through the fields, preventing the user from entering any data.
How do I fix this problem?
I think this is what you want:
Demo
Instead of validating all inputs onblur, just validate the one that left focus. To do that I have passed in the element to Validate(this) in the HTML inline code. You also had some element ID issues (e.g. no message field). I also added a .focus() call to keep the input in focus if it's invalid.
function Validate(elem) {
// create array containing textbox elements
var input = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email1'), document.getElementById('email2'), document.getElementById('message')];
for (var i = 0; i < input.length; i++)
// loop through each element to see if value is empty
{
if (input[i].value == '' && elem.id == input[i].id) {
switch (input[i].id) {
case 'fname':
alert('enter you first name');
break;
case 'lname':
alert('enter your last name');
break;
case 'email1':
alert('enter your email address');
break;
case 'email2':
alert('enter your email address');
break;
case 'message':
alert('write your message');
break;
}
elem.focus();
}
}
}
I have to say though that lots of alert()'s are pretty nasty, it would be much better if you show a span next to each textbox with the error message instead.
I'm afraid you have to rethink the whole validation code. Next is happening:
User inputs "First Name"
Script iterates through input array
round1: is fname OK --> yes, next i
round2: is lname OK --> no, show alert
round3: is email1 OK --> no, show alert
...
When this is iterated and the user finally can input the next field, the above loop is executed again, though there will be one alert less per each new loop.
A simple fix would be something like this:
function Validate(id) {
var errors = {
fname: 'enter you first name',
lname: 'enter your last name',
email1: 'enter your email address',
email2: 'enter your email address',
message: 'write your message'
};
if (document.getElementById(id).value === '') {
if (id in errors) {
alert(errors[id]);
}
}
return;
}
In HTML just pass the corresponding id to Validate():
<input class="input" type="text" name="fname" id="fname" onblur="Validate('fname')" />
However, I'd find this annoying behavior. It would be more comfortable, if you made the validation on submit, and cancel submit, if there are empty fields.

Customizing the message in a jQuery validate custom rule

I have a custom jQuery validate rule called fiftyCents() where there are two rules:
if the item is free, one can "buy" it for $0.00 or they can pay greater than $0.50.
if the item is NOT free, then they must pay at least the cost specified (stored in a hidden cachedValue input field).
So those are my two validation error messages. The problem I'm having in adding these to fiftyCents() is that I can only figure out how to evaluate it as true/false and if false, display a single message, e.g., "Amount must be $0.00 OR greater than $0.50.".
The solution to the JSfiddle (code below too) appears to be to make a message object that could be part of the fiftyCents() function. However, I don't know how to return that along with evaluating true/false. Thoughts?
JS:
$('button').click(function(){
$('form').validate().form();
});
$.validator.addMethod("fiftyCents", function(value) {
var cachedValue=$('.purchaseModalAmtPaidCached').val();
var value = $('.purchaseModalAmtPaid').val();
var message="Amount must be $0.00 OR greater than $0.50.";
if(cachedValue>0) message='Amount must be at least'+cachedValue+'.';
return cachedValue<=value && (value==0 || (0.51<=value && value<=10000));
}, message);
$.validator.classRuleSettings.purchaseModalAmtPaid = { fiftyCents: true };
HTML:
<form>
<input class="purchaseModalPassword required" minlength="8" type="password"name="password" value="dddddddv" title="Please enter a valid password" />
<input type="text" title="Amount must be $0.00 OR greater than $0.50"
class="required purchaseModalAmtPaid" name="amt_paid" value="" />
<input type="hidden" class='purchaseModalAmtPaidCached required' name="AmtPaidCached" value="0.00" />
<button type='button'>Buy</button>
</form>​
Ok I answered my own question. What I ended up doing is splitting up the two rules into their own custom methods. I used an if/else before either custom method is invoked to determine which of the two should be followed.
Here's the JSFiddle and code below:
JS:
$('button').click(function(){
$('form').validate().form();
});
var params=$('.purchaseModalAmtPaidCached').val();
if(params>0){
$.validator.addMethod("AmountOrGreater", function(value, element, params) {
console.log('amountOrGreater'+params[0]);
return params[0]<=value && (value==0 || (0.51<=value && value<=10000));
}, $.validator.format("Amount must be at least {0}."));
$.validator.classRuleSettings.purchaseModalAmtPaid = { AmountOrGreater: params };
}
else{
$.validator.addMethod("fiftyCents", function(value, element, params) {
console.log('fiftyCents'+params[0]);
return params[0]<=value && (value==0 || (0.51<=value && value<=10000));
}, "Amount must be $0.00 OR greater than $0.50.");
$.validator.classRuleSettings.purchaseModalAmtPaid = { fiftyCents: params };
} //else
HTML:
<form>
<input class="purchaseModalPassword required" minlength="8" type="password" name="password" value="dddddddv" title="Please enter a valid password" />
<input type="text"
class="required purchaseModalAmtPaid" name="amt_paid" value="" />
<input type="hidden" class='purchaseModalAmtPaidCached required' name="AmtPaidCached" value="0.00" />
<button type='button'>Buy</button>
</form>​
Note: A key to the HTML cooperating with jQuery validate is that if you give your inputs a title='' attribute then that title will always be used, thus overriding the message in your custom rule. This is relevant in my case b/c there were two custom rules/messages and I'm not able to determine in advance of the HTML being rendered which one the user would see.

Categories