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.
Related
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.
<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;
}
I am trying form validation in Javascript, but I am stuck on something.
I have gotten the validation working, but cannot display the contents of each field in the textarea of the form at the bottom.
Any idea how I would do this?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function validate() {
if( document.myForm.room.value == "" ) {
alert( "Please select a room option." );
return false;
}
if( document.myForm.activity.value == "" ) {
alert( "Please select an activity." );
return false;
}
if( document.myForm.hotelname.value == "-1" ) {
alert( "Please select a hotel name." );
return false;
}
if( document.myForm.name.value == "" ) {
alert( "Please provide your name." );
document.myForm.Name.focus() ;
return false;
}
// Use isNaN to check whether there is an illegal number
if( document.myForm.zip.value == "" ||
isNaN( document.myForm.zip.value ) ||
document.myForm.zip.value.length != 5 ) {
alert( "Please provide a zip code in 5 digit format." );
document.myForm.zip.focus() ;
return false;
}
return( true );
}
</script>
</head>
<body>
<form name="myForm" action="" onsubmit="return(validate());">
Type of room: <br />
<input type="radio" name="room" value="basic">Basic<br>
<input type="radio" name="room" value="luxury">Luxury
<br /><br />
Activity: <br />
<input type="checkbox" name="activity" value="swimming">Swimming<br>
<input type="checkbox" name="activity" value="fishing">Fishing
<br /><br />
Hotel name: <br />
<select name="hotelname" multiple="multiple">
<option value="-1" selected>Select...</option>
<option value="1">Hilton</option>
<option value="2">Hampton Inn</option>
<option value="3">Holiday Inn</option>
</select>
<br /><br />
Conferee's name:<input type="text" name="name">
<br /><br />
Conferee's zip code:<input type="text" name="zip">
<br /><br />
<input type="submit" value="Submit" />
<br /><br />
<textarea rows="10" cols="50"></textarea>
</form>
</body>
</html>
// Use isNaN to check whether there is an illegal number
if( document.myForm.zip.value == "" ||
isNaN( document.myForm.zip.value ) ||
document.myForm.zip.value.length != 5 ) {
alert( "Please provide a zip code in 5 digit format." );
document.myForm.zip.focus() ;
return false;
}
// create the textarea content string
var fields_contents = "";
fields_content += "room : " + document.myForm.room.value + "\n";
fields_content += "activity : " + document.myForm.activity.value + "\n";
fields_content += "hotelname : " + document.myForm.hotelname.value + "\n";
fields_content += "name : " + document.myForm.name.value + "\n";
fields_content += "zip : " + document.myForm.zip.value + "\n";
//set the textarea content
document.getElementById('my_textarea').value = fields_content;
//and then return false for the form not to be submitted
return false;
Notice I use an id to find the textarea : you should add it in your html.
The \n char is line break.
This version implies your form not to be submitted. The thing is that here we get inputs values directly by reading their value property. If the form was submitted, the page would be refreshed, and the inputs values would be empty then.
In this case, the solution would be to get the sent values with PHP, and then use these values directly in Javascript, like that :
var room_value_sent = '<?php echo $_REQUEST['room']; ?>';
fields_content += "room : " + room_value_sent + "\n";
The return false at the end is because of the need not to submit the form. When you do something like onsubmit="return my_function();", if my_function returns false then the form is not submitted (= no page refresh and no request is done).
Sorry for answering instead of commenting - repuration limitations. You can try using Parsley.js library which provides clean code and works out of the box for almost any form you can imagine. Have a look here:
Parlsey.js
I have a form that has some simple javascript to validate a simple questionnaire. It used the name attribute on inputs in the form but now the page is integrated with the clients CMS it needs to use a particular naming convention which I can't get to work.
The old form had inputs like this:
<input type="text" name="firstName" />
but with the cms all fields require "fields[firstName]", e.g.:
<input name="fields[first-name]">
How do I get this to work.
Exisiting JS below:
function validate_form ( )
{
valid = true;
if ( ( document.register.question[0].checked == false ) && ( document.register.question[1].checked == false ) && ( document.register.question[2].checked == false ) )
{
alert ( "Please choose an answer" );
valid = false;
}
else if ( document.register.form_title.value == "" )
{
alert ( "Please fill in the 'Title' box." );
valid = false;
}
else if ( document.register.fName.value == "" )
{
alert ( "Please add your First Name" );
valid = false;
}
else if ( document.register.lName.value == "" )
{
alert ( "Please add your Last Name" );
valid = false;
}
else if ( document.register.email.value == "" )
{
alert ( "Please add a valid email address" );
valid = false;
}
else if ( document.register.country.selectedIndex == 0 )
{
alert ( "Please select your Country" );
valid = false;
}
else if ( document.register.dob1.selectedIndex == 0 )
{
alert ( "Please ensure your date of birth is complete" );
valid = false;
}
else if ( document.register.dob2.selectedIndex == 0 )
{
alert ( "Please ensure your date of birth is complete" );
valid = false;
}
else if ( document.register.dob3.selectedIndex == 0 )
{
alert ( "Please ensure your date of birth is complete" );
valid = false;
}
else if ( document.register.terms.checked == false )
{
alert ( "Please check the Terms & Conditions box." );
valid = false;
}
return valid;
}
you can use jquery with something like this:
$("input[name=fields\\[first-name\\]]").val()
I'm just starting to use JQuery, and I'm editing the modal popup example within a classic asp page. I've gotten the form to work, and added a submit line, but after the submit I try to get the submitted values with asp using request.form("email") but it's coming up blank.
Is this a problem with how I'm submitting, how I'm reading the values, or something else? What do I need to do to submit the form and get the values?
Here's the code:
I call the dialog with this:
<strong>Forgot your login?:</strong> click here</p>
The dialog form:
<div id="dialog-form" title="Send My Login">
Enter the email address associated with your account. Your password will be sent to you.
<br />
<strong>If you do not have an email address</strong>, or do not
remember it, please contact your Human Resources department to have your login
provided to you.
<p class="validateTips">
</p>
<form action="SendLogin.asp" method="Post" name="modalPopup">
<fieldset>
<label for="email">Email</label>
<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
The dialog code:
<script type="text/javascript">
$(function () {
//Modal pop-up form
// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
$("#dialog:ui-dialog").dialog("destroy");
var email = $("#email"),
allFields = $([]).add(email);
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;
}
}
$("#dialog-form").dialog({
autoOpen: false,
height: 350,
width: 350,
modal: true,
buttons: {
"Send Login": function () {
var bValid = true;
allFields.removeClass("ui-state-error");
bValid = bValid && checkLength(email, "email", 5, 80);
// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
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, "Please enter a valid email address.");
if (bValid) {
$("#users tbody").append("<tr>" +
"<td>" + email.val() + "</td>" +
"</tr>");
$(this).dialog("close");
$("form[name='modalPopup']").submit()
}
},
Cancel: function () {
$(this).dialog("close");
}
},
close: function () {
allFields.val("").removeClass("ui-state-error");
}
});
$("#send-password")
.click(function () {
$("#dialog-form").dialog("open");
});
});
</script>
The form is submitted to SendLogin.asp and I try to receive the value with this:
<%tempEmail=request.form("email")%>
But tempEmail is coming up blank when I try to print it afterward. What do I need to do to get the submitted form values?
Any help is appreciated!
Try changing your submit to this:
document.modalPopup.submit();