Fixing Validation on Input Field - javascript

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.

Related

How to customize validation message position in login validation?

<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;
}

jquery autocomplete by textbox value

let u as consider the value am having in textbox so now if we type in that it automatically
have to show word with multi-value by comma. I have tried but no result.
Can any body help out of this problem.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(function()
{
var val = document.getElementById('tags').value;
var availableTags = val == '' : [] ? val.split(',');
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#tags" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tag programming languages: </label>
<input id="tags" size="25" value="ACCENTURE 1,
BPCL KORAMANGALA,
CUNNIGHAM ROAD,
HM TOWERS,
GREATER NOIDA,
INFOSYS 3,
JAYANAGAR T BLOCK,
MILLENIA,
OZONE,
BKC,
FUN REPUBLIC,
MATUNGA,
VFS UK,
CYBER GREEN,
PRABHADEVI,
VRINDAVAN"/>
</div>
As per my understanding, your autocomplete(which I have tested in fiddle) is not populating. The reason is you ternary operator syntax is wrong.
var availableTags = val == '' : [] ? val.split(','); //WRONG
Change this to
var availableTags = val == '' ? [] : val.split(','); //CORRECT
See it is working in JSFiddle

Update modal jquery box is not working

I had a create jquery modal box with validation and its working. But for my update jquery modal box, its not working. The bvalid isnt running the validation as I've tried to submit the form in the cancel button and it works. Let me show you guys the codes.
$(function() {
var username = $( "#username" ),
email = $( "#email" ),
password = $( "#password" ),
accountexpired = $( "#account_expired" ),
allFields = $( [] ).add( username ).add( email ).add( password ).add( accountexpired ),
tips = $( ".validateTips" );
function updateTips( t ) {
tips
.text( t )
.addClass( "ui-state-highlight" );
setTimeout(function() {
tips.removeClass( "ui-state-highlight", 1500 );
}, 500 );
}
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min ) {
o.addClass( "ui-state-error" );
updateTips( "Length of " + n + " must be between " +
min + " and " + max + "." );
return false;
} else {
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) ) {
o.addClass( "ui-state-error" );
updateTips( n );
return false;
} else {
return true;
}
}
$( "#edit1" ).dialog({
autoOpen: false,
height: 700,
width: 500,
modal: true,
buttons: {
"Update": function() {
var bValid = true;
allFields.removeClass( "ui-state-error" );
bValid = bValid && checkLength( username, "Length of username must be between 3 and 16. Username may consist of a-z, 0-9, underscores, begin with a letter. ", 3, 16 );
bValid = bValid && checkLength( email, "Length of email must be between 6 and 80. eg. ui#mail.com", 6, 80 );
bValid = bValid && checkLength( password, "Length of password must be between 5 and 16. Password field only allow : a-z 0-9", 5, 16 );
bValid = bValid && checkRegexp( username, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui#jquery.com" );
bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );
if ( bvalid ) {
$( this ).dialog( "close" );
$('#editUser').submit();
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
As for the html:
<%--Update user box --%>
<div id="edit1" title="Update user">
<form id="editUser" method="post" name="editUser">
<p class="validateTips"><g:message code="default.error.requiredforms.message" />.</p>
<g:each in="${Query1}">
<table id="editpage" style="border-collapse: collapse;">
<tr>
<td><label for="username"><g:message code="default.searchcustomer.username.message" />:</label></td>
<td><input type="hidden" name="username" id="username"
style="border: 1px solid black" value="${it.username}" /><label>${it.username}</label></td>
</tr>
<tr>
<td style="white-space: nowrap"><label for="account_expired"><g:message code="default.searchcustomer.accexpired.message" />:</label></td>
<td style="text-align: left"><input type="radio"
name="account_expired" id="account_expired" value="${true}"
${it.account_expired == true ? 'checked="checked"' : ''}>
True <input type="radio" name="account_expired" id="account_expired" value="${false}"
${it.account_expired == false ? 'checked="checked"' : ''}>
False</td>
</tr>
<tr>
<td><label for="password"><g:message code="default.searchcustomer.password.message" />:</label></td>
<td><input type="password" name="password" id="password"
style="border: 1px solid black" value="${it.password}" /></td>
</tr>
<tr>
<td><label for="email"><g:message code="default.searchcustomer.email.message" />:</label></td>
<td><input type="text" name="email" id="email"
style="border: 1px solid black" value="${it.email}" /></td>
</tr>
</table>
</g:each>
</form>
</div>
I did implement some ajax into this but I have no idea why the validation is not working and preventing me from submitting the form. Any guys out there can help me with this? Thank you guys so much.
Define action in form
<form id="editUser" method="post" name="editUser" action="">
It appears you are outputting the "editpage" table inside a loop. If more than one is output, you end up with many elements having the same names and ids, which is invalid. When clicking "Update", maybe the validation looks at the first fields having the ids involved, and not the ones you are trying to validate.
All this provided, of course, that ${Query1} returns more than one row.
If the dialog is removed but the form not submitted when clicking Update, I guess it's also worth trying to submit the form before closing the dialog, though I doubt it would make a difference as closing the dialog just hides it afaik.

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.

Having Jquery ui issue

I placed all code below. My page works like that
Page's first scene
When i choose something from #menu it fires $("#menu").change(function () function and i'm getting scene like that
Radio buttons .parentcheck are located in div #options. They're like turn off (first one)/on (second one) select-box #parent.
When i turn #parentselectbox on, it fires genopts- ajax request and on success it transforms select-box into jquery-ui autocomplete combobox and places default value.
Now, the problem is following
I'm using input.val( $("#parent option:selected").text()); (in combobox configuration) to place default value. The problem is i want to remove this text onclick (something like html5 placeholder but i want crossbrowser support). How to modify the combobox configuration part to fix that problem?
HTML Markup
<table>
<tr>
<td><label for="menu" id="menu_label">Səhifə harada yerləşəcək?</label>
<select name="menu" id="menu">
<option value="" selected="selected">Birini seçin...</option>
<option value="1">Header menyuya əlavə et</option>
<option value="2">Footer menyuya əlavə et</option>
<option value="0">Bu səhhifənin menyuda adı olmayacaq</option>
</select></td>
<td><div id="options">
<input type="radio" class="parentcheck" name="parentcheck" value="0"/>
Ayrıca yoxsa
<input type="radio" class="parentcheck" name="parentcheck" value="1"/>
hansısa başlıq altında? </div>
<select name="parent" id="parent">
</select></td>
</tr>
</table>
The combobox configuration
(function( $ ) {
$.widget( "ui.combobox", {
_create: function() {
var self = this,
select = this.element.hide(),
selected = select.children( ":selected" ),
value = selected.val() ? selected.text() : "";
var input = this.input = $( "<input>" )
.insertAfter( select )
.val( value )
.autocomplete({
delay: 0,
minLength: 0,
source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( select.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" ),
value: text,
option: this
};
}) );
},
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
change: function( event, ui ) {
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
valid = false;
select.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
}
})
.addClass( "ui-widget ui-widget-content ui-corner-left" );
input.val( $("#parent option:selected").text());
input.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
this.button = $( "<button type='button'> </button>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.insertAfter( input )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon" )
.click(function() {
// close if already visible
if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
input.autocomplete( "close" );
return;
}
// work around a bug (likely same cause as #5265)
$( this ).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
input.focus();
});
},
destroy: function() {
this.input.remove();
this.button.remove();
this.element.show();
$.Widget.prototype.destroy.call( this );
}
});
})( jQuery );
1st problem answer:
http://forum.jquery.com/topic/disable-autocomplete
2nd problem answer:
You can put this text to the title attribute of the your input and then on focus check your value if it's the same as in title. Change your input.val( $("#parent option:selected").text()); to:
var emptyText = $("#parent option:selected").text();
input.attr('title', emptyText).val(emptyText);
input.focus(function() {
var $this = $(this);
if ($this.val() == $this.attr('title')) {
$this.val('');
}
});
input.blur(function() {
var $this = $(this);
if ($this.val() == '')
$this.val($this.attr('title'));
});

Categories