How to customize validation message position in login validation? - javascript

<input type="text" class="form-control"
name="username" placeholder="Enter ID" required
oninvalid="this.setCustomValidity('Enter ID')"
oninput="setCustomValidity('')" />
How to customize the Validation message position to the right of the textbox? Now it's coming below the textbox.
Plunker link: http://plnkr.co/edit/vvfR5pelzeJAMM5LagC9?p=preview

Using of positions to the element for parent element use relative and use position absolute for tooltip. If possible show your demo code.

Here is an example with jQuery dependent script.
<div>
<label for="name">Name:</label>
<input id="name" type="text" required>
</div>
<div>
<label for="comments">Comments:</label>
<textarea id="comments" required></textarea>
</div>
<div class="buttons">
<button>Submit</button>
</div>
</form>​
<script>
var createAllErrors = function() {
var form = $( this ),
errorList = $( "ul.errorMessages", form );
var showAllErrorMessages = function() {
errorList.empty();
// Find all invalid fields within the form.
var invalidFields = form.find( ":invalid" ).each( function( index, node ) {
// Find the field's corresponding label
var label = $( "label[for=" + node.id + "] "),
// Opera incorrectly does not fill the validationMessage property.
message = node.validationMessage || 'Invalid value.';
errorList
.show()
.append( "<li><span>" + label.html() + "</span> " + message + "</li>" );
});
};
// Support Safari
form.on( "submit", function( event ) {
if ( this.checkValidity && !this.checkValidity() ) {
$( this ).find( ":invalid" ).first().focus();
event.preventDefault();
}
});
$( "input[type=submit], button:not([type=button])", form )
.on( "click", showAllErrorMessages);
$( "input", form ).on( "keypress", function( event ) {
var type = $( this ).attr( "type" );
if ( /date|email|month|number|search|tel|text|time|url|week/.test ( type )
&& event.keyCode == 13 ) {
showAllErrorMessages();
}
});
};
$( "form" ).each( createAllErrors );
</script>

You can customize the validation message position by adding this CSS code.
.form-control[required] {
margin-top: 40px !important;
margin-left: 100px !important;
}

Related

Unable to submit form even when input is not empty

So I'm working on a simple form where I'm checking if the input is empty. If it is then it should stop the form submission but if its not then it will go ahead and submit the form.
Right now, when the input field is empty and I press the submit button, the error message is displayed. But if I type something on the input field and try to submit, the code inside the if block triggers again and the form doesn't submit.
Why would the code inside the if block trigger again when the input is not empty? Wouldn't it just skip the if statement altogether and submit the form?
Here's the code:
HTML
<div class="name-search" >
<form action="/send" method="POST" >
<input class="search_input" name="name" type="text">
<button type="submit" class="search_icon"><i class="fas fa-search"></i></button>
<p class="error-msg"></p>
</form>
</div>
JS
const form = $( '.name-search form' );
const formInputVal = $( '.name-search form .search_input' ).val();
const formErrorMsg = $( '.name-search form .error-msg' );
$( form ).submit( ( e ) => {
if ( formInputVal === '' ) {
$( formErrorMsg ).text( 'Input field can\'t be empty.' );
return false;
}
return true;
});
When you put the value in a variable, that's it, you do it once, the variable doesn't change when the value does, so instead, you need to get the value everytime:
const form = $( '.name-search form' );
const formInput = $( '.name-search form .search_input' );
const formErrorMsg = $( '.name-search form .error-msg' );
$( form ).submit( ( e ) => {
if ( formInput.val() === '' ) {
$( formErrorMsg ).text( 'Input field can\'t be empty.' );
return false;
}
return true;
});

How to keep data-fixedvalue in different textboxes?

I have two different textboxes and a function to keep some part of values in each of them even if the user deletes textboxes data-fixedvalue will be back .
I worte the below code but this code only works for the first class for the next class it does not consider data-fixedvalue.
How can I fix this issue?
Here is my snippet :
var el = document.querySelector( ".telinfo" );
el.addEventListener( "keyup", handleEv);
el.addEventListener( "blur", handleEv);
function handleEv( event )
{
var thisObj = event.currentTarget;
var fixedValue = thisObj.getAttribute( "data-fixedvalue" );
if ( thisObj.value.indexOf( fixedValue ) != 0 )
{
console.log(thisObj.value, fixedValue);
event.preventDefault();
thisObj.value = fixedValue;
}
}
<input type="text" value="+98912314789" class="telinfo" data-fixedvalue = "+9891" maxlength="13">
<input type="text" value="+7812345678" class="telinfo" data-fixedvalue = "+78">
You were almost there. You have multiple elements so use document.querySelectorAll( ".telinfo" ) and then iterate over all of them (it's an array) with forEach() cause you need to add the event listener to every element you want to handle the event.
var elements = document.querySelectorAll( ".telinfo" );
elements.forEach(function(element){
element.addEventListener( "keyup", handleEv);
element.addEventListener( "blur", handleEv);
});
function handleEv( event ) {
var thisObj = event.currentTarget;
var fixedValue = thisObj.getAttribute( "data-fixedvalue" );
if ( thisObj.value.indexOf( fixedValue ) != 0 ) {
console.log(thisObj.value, fixedValue);
event.preventDefault();
thisObj.value = fixedValue;
}
}
<input type="text" value="+98912314789" class="telinfo" data-fixedvalue = "+9891" maxlength="13">
<input type="text" value="+7812345678" class="telinfo" data-fixedvalue = "+78">

Fixing Validation on Input Field

I have a dialog box that pops up after hitting an Add button. There are 2 fields, MR ID and Supplier ID. MR ID is a dropdown and shouldn't need any sort of validation. The supplier id is a text input and needs validation. It needs to be numbers only and there also can be no 2 supplier ids that are the same. They must all be unique. The code I have so far does not work in validating the supplier id.
HTML/PHP for dialog box:
<div id="dialog-form" title="Add Supplier ID">
<p class="validateTips">All form fields are required.</p>
<!-- Dialog box displayed after add row button is clicked -->
<form>
<fieldset>
<label for="mr_id">MR_ID</label>
<select name="mr_id" id="mr_id_dialog" class="text ui-widget-content ui-corner-all" value="300">
<?php foreach($user->fetchAll() as $user1) { ?>
<option>
<?php echo $user1['MR_ID'];?>
</option>
<?php } ?>
</select><br><br>
<label for="supplier_id">Supplier ID</label>
<input type="text" name="supp_id" id="supplier_id" class="text ui-widget-content ui-corner-all" value="99">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
JavaScript:
// ----- Dialog Box for adding supplier id -----
$(document).ready( function() {
$("#insertButton").on('click', function(e){
e.preventDefault();
});
var dialog, form,
mr_id_dialog = $( "#mr_id_dialog" ),
supplier_id = $( "#supplier_id" ),
allFields = $( [] ).add( mr_id_dialog ).add( supplier_id ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
function addVendor() {
var valid = true;
allFields.removeClass( "ui-state-error" );
// ----- Validation for each input in add row dialog box -----
//valid = valid && checkRegexp( mr_id_dialog, /^(0|[1-9][0-9]*)$/, "Please enter a valid MR ID" );
valid = valid && checkRegexp( supplier_id, /^(0|[1-9][0-9]*)$/g, "Please enter a valid Supplier ID" );
if ( valid ) {
var $tr = $( "#index_table tbody tr" ).eq(0).clone();
var dict = {};
var errors = "";
$.each(allFields, function(){
$tr.find('.' + $(this).attr('id')).html( $(this).val()+"-"+supplier_id );
var type = $(this).attr('id');
var value = $(this).val();
// ----- Switch statement that provides validation for each table cell -----
switch (type) {
case "mr_id_dialog":
dict["MR_ID"] = value;
break;
case "supplier_id":
dict["Supp_ID"] = value;
break;
}
});
$( "#index_table tbody" ).append($tr);
dialog.dialog( "close" );
}
}
var dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Add Supplier ID": addVendor,
Cancel: function() {
dialog.dialog( "close" );
}
},
close: function() {
form[ 0 ].reset();
allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" ).on( "submit", function( event ) {
event.preventDefault();
addVendor();
});
$( "#insertButton" ).button().on( "click", function() {
dialog.dialog({
position: ['center', 'top'],
show: 'blind',
hide: 'blind'
});
dialog.dialog("open");
});
});
Samples that should pass:
349348
2
1234
Samples that should not pass:
01234
123 45 67
No hyphens, dashes, etc. Numbers only.

alert box not stopping execution/submission of the form

This is a code snippet I'm using. Here as per my expectation, code execution doesn't stop and the form gets submitted. Though alert box appears but after pressing "ok" the form get submitted.
$('.qto').each(function(index) {
if (jQuery.inArray($("#quota-" + (index + 1)).val(), quoatas) != -1) {
alert("Please check the different values you have entered");
return false;
}
quoatas.push($("#quota-" + (index + 1)).val());
});
The issue is because your return false is relevant to the anonymous function it's contained in, not the submit handler of the form (which I'm presuming this code is contained within). As a workaround, you can use the preventDefault() method of the event which is passed to the submit handler. Try this:
$('#myForm').submit(function(e) {
$('.qto').each(function(index) {
if ($.inArray($("#quota-" + (index + 1)).val(), quoatas) != -1) {
e.preventDefault(); // stop the form submission
alert("Please check the different values you have entered");
}
quoatas.push($("#quota-" + (index + 1)).val());
});
});
you can use preventDefault() to stop form submission
You can simply use event handler which is bound to the form like this,
<!doctype html>
<html>
<head>
<title>Form Submit Handler</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Enter 'demo' as valid data: </p>
<form id="formId" action="javascript:alert( 'Value Valid. Form submitted.' );">
<div>
<input id="firstName" type="text">
<input type="submit" value="Check">
</div>
</form>
<p id="response" style="color:red;"></p>
<script>
$( "#formId" ).submit(function( event ) {
if ( $( "#firstName" ).val() === "demo" ) {
$( "#response" ).empty();
$( "#response" ).text( "Submitted." ).show();
return;
}
$( "#response" ).empty();
$( "#response" ).append( "Not submitted." );
event.preventDefault();
});
</script>
</body>
</html>

Mask and unmask input text in html

I have few text fields like SSN , phone number and email id. I would like to do something like onfocus it should display the whole content of that input box and on blur it should mask the content back to something (say asterix).Thanks in advance
You could switch the type of the <input> element between password and text in both events. See this example fiddle.
HTML
<input type="password" id="target" />
JS
<script>
var inp = document.querySelector( '#target' );
inp.addEventListener( 'focus', function(){
inp.type = 'text';
});
inp.addEventListener( 'blur', function(){
inp.type = 'password';
});
</script>
Try it like this:
<input type="text" id="emailId" name="emailId" />
Then, do a:
var emailIdValue = "";
$( document ).ready( function() {
emailIdValue = $( '#emailId' ).val();
$( '#emailId' ).val( "********" );
$( '#emailId' ).focus( function() {
$( this ).val( emailIdValue );
} ).focusout( function() {
emailIdValue = $( this ).val();
$( this ).val( '********' );
} );
} );
You could simply use <input type="password" /> if you want to do it simple.

Categories