jquery validation of text field not firing ajax request for valid entry - jquery-validate

I have a text field(email) in my form which checks whether the entered value is valid, if so then it will have to validate the same again my DB.
The problem is that when I type wrong its not displaying the error message that I have configured under message, instead it chooses over the default msg.
$("#myform").validate({
rules: {
email:{
required: true,
email: true,
type: "post",
remote:{
url:"myservlet?verifyEmail=checkEmail",
/* data: "verifyEmail=checkEmail", */
type: "post",
}
},
messages:{
email:{
required: "Enter a valid email",
remote: "This user is already taken"
}
}
},
highlight: function(element){
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element){
element
.closest('.control-group').removeClass('error')/* .addclass('error') */;
}
});
if(('#myform').validated())
('#myform').submit();
I tried to check the network traffic i dnt see any traffic due to this request. The bootstrap class configured under highlight and success is working fine. This is my first time using this plugin.
Update 1: Input controls
<div class="control-group">
<label class="control-label" for="email"> email:</label>
<div class="controls">
<input type="text" id="email" class="input-xlarge span2" name="email"/>
</div>
</div>
<tr>
<td></td>
<td><input type="button" Value="Refresh" /></td>
</tr>
Update 2:
I have modified my code. Now validation rules is working, but I am still facing issues with ajax request not being fired. Any heads up on that?

Try this - I've update the object structure slightly, messages is a sibling of rules, not a child:
$("#myForm").validate({
rules: {
email: {
required: true,
email: true,
type: "post",
remote: {
url: "myservlet?verifyEmail=checkEmail",
/* data: "verifyEmail=checkEmail", */
type: "post",
}
}
},
messages: {
email: {
required: "Enter a valid email",
remote: "This user is already taken"
}
}
});
DEMO

Related

ko async validation plugin

[UPDATED]
I am not sure how to add a custom (html) message to my async knockout validator.
Below is a simple form. You can see that there is already some isModified and isValid validation in-place, but it is not async. (I am not sure if this complicates or simplifies the solution.)
<form
method="post"
action="Registration()"
novalidate
data-bind="submit: onRegister">
<div
class="input-wrapper email"
data-bind="
validationOptions: {
messageTemplate: 'emailCollisionTemplate'
},
validationElement: EmailAddress,
css: { 'validation-success': EmailAddress.isModified() && EmailAddress.isValid() }">
<input
type="email"
id="registerModalEmail"
data-bind="
value: EmailAddress,
ariaInvalid: EmailAddress"
aria-describedby="email-address-error"
required />
</div>
<div
class="validation-error-message"
id="email-address-error"
data-bind="validationMessage: EmailAddress">
</div>
</form>
<script type="text/html" id="emailCollisionTemplate">
<span>This email is already registered. Please sign in.
</span>
</script>
And then some js:
self.EmailAddress = ko.observable().extend({
required: {
params: true,
message: 'required'
)
},
pattern: {
params: '#',
message: 'match'
)
},
validation: {
async: true,
validator: function (val, parms, callback) {
$.ajax({
url: 'myUrl/isEmailAllowed',
data: { 'EmailAddress': val },
type: 'POST',
success: function (results) {
if (results) {
callback(true);
}
},
error: function (xhr) {
callback(false);
}
});
}
}
});
(isModified and isValid is handled elsewhere, so I have not included it.)
How do I configure the messageTemplate to show? I've looked at examples, but none of them seem to match what I'm doing here. I've put the validationOptions into the data-bind like it seems to say, but that's not working.
I should point out two confounding aspects here:
There are other validators on this same field (i.e.required and pattern)
There are other fields in this form with validation. (The configuration object says the messageTemplate should be 'id of the script that you want to use for all your validation messages'. I only want it for this one field.)

Durandal: Ajax get request displays blank page rather than my customize spinning

Problem/Unwanted Result: In addition to displaying my composed "spinning icon", it displays a blank page while the request is in process and then the blank page is gone after it is done.
Purpose: I am trying to display a list of events as Json from a server asynchronously. When it is in progress, I want to display my customized spinning icon.
How: I have event.hmtl and event.js. I use "durandal compose" to compose either "view of event list from the server" or "the spinning icon".
1- When I click on a refresh button, it will call "refreshEvent" function to compose "spinning icon" while processing.
2- The refreshEvent will do ajax call to server to get the event list.
3- After it is done, I bind the result to observable data and compose "event list view" instead.
Event.html:
<div class="row">
<div class="col-lg-11 col-md-11 col-sm-11">
<h1>Upcoming events</h1>
</div>
<div class="col-lg-1 col-md-1 col-sm-1">
<span class="icon glyphicon glyphicon-refresh" data-bind="click: refreshEvent"></span>
</div>
</div>
<div class="h-events row">
<div data-bind="compose: { view: upcoming_event activationData: $root }"></div>
</div>
<div class="clearfix"></div>
</div>
Event.js:
define('services/logger', 'durandal/system', 'durandal/activator', 'plugins/router', 'durandal/app', 'services/errorhandler', 'jquery'],
function (logger, system, activator, router, app, errorhandler, $) {
var view = {
progress: 'partials/_progress.html',
upcoming_event: 'partials/_upcoming-event.html',
};
var vm = {
activate: activate,
events: ko.observable(),
upcoming_event: ko.observable(view.progress),
feed_view: ko.observable(view.progress),
refreshEvent: refreshEvent,
even_detail :
{
description: ko.observable(),
title: ko.observable(),
date: ko.observable(),
month: ko.observable(),
time: ko.observable(),
name: ko.observable().extend({
required: { message: 'Name is required' },
minLength: { message: 'Name must be at least 3 characters', params: 3 }
}),
team_name: ko.observable().extend({
required: { message: 'Team name is required' },
minLength: { message: 'Team name must be at least 3 characters', params: 3 }
}),
email: ko.observable().extend(
{
required: { message: 'Email is required' },
email: { message: 'Email must be in correct format e.g. example#domain.com' }
}),
phone: ko.observable().extend({
required: { message: 'Phone number is required' },
number: { message: 'Phone must be number and no spaces' },
minLength: { message: 'Phone number must be at least 9 digits', params: 9 }
}),
message: ko.observable(),
event_id: "",
event_detail_view: ko.observable(),
old_event_view : "",
}
};
vm.errors = ko.validation.group(vm, { deep: true, observable: false, live: false });
function refreshEvent() {
vm.upcoming_event(view.progress); //display spinning icon
Q.when($.ajax({
url: '/breeze/feed/FeedAndEvent',
type: 'GET',
contentType: 'application/json',
dataType: 'json'
})).then(function (result) {
vm.upcoming_event(result); //display
vm.upcoming_event(view.upcoming_event);
}).fail(errorhandler);
}
function activate() {
}
return vm;
});
I can see what you are trying to do. I am not sure it is possible to switch out just the view portion of the compose binding and expect it to update. You may need to compose directly to an observable that contains a reference to the desired viewmodel that you wish to display at any point in time.
However, try fixing this first. There is a mistake in the compose binding:
<div data-bind="compose: { view: upcoming_event activationData: $root }"></div>
<!-- Should have a comma after upcoming_event -->
<div data-bind="compose: { view: upcoming_event, activationData: $root }"></div>

jQuery validate plugin: use different multilingual error message on each required input box

I am using jQuery validate plugin, suppose I have 3 input box and they are required fields.
<input type="text" name="firstname" class="required" />
<input type="text" name="lastname" class="required" />
<input type="text" name="email" class="required" />
I want to have different error message, so I configure as below:
$("#myForm").validate({
messages: {
firstname: {
required: 'Please enter firs tname'
},
lastname: {
required: 'Please enter last name'
},
email: {
required: 'Please enter email'
}
},
submitHandler: function(form) {
form.submit();
}
});
However, now I want to have different multilingual error message on each required input box, so I tried to configure as below, the result is not work.
$("#myForm").validate({
messages: {
firstname: {
required: window.lang.currentLang == 'en' ? 'Please enter email' : '請輸入電子郵件地址'
}
},
submitHandler: function(form) {
form.submit();
}
});
Could someone advise the way to configure the plugin to have different multilingual error message.
Thanks

jQuery validation: inputs disappearing after all pass verification

Unable to figure this one out...
In the below form, all of the inputs disappear as soon as validation passes on all of them, leaving nothing but the submit button visible.
For example, if I click "submit" on this form before completion, all unfinished fields are given the ".incomplete" error class to mark them incorrect. If I then go through the inputs one by one and complete them, the error class disappears. But as soon as the last-remaining input is completed and the error class is removed, all of the inputs disappear leaving just "submit".
I can tell it has something to do with the .incomplete CSS class, which is applied whenever the user clicks "submit" without having all fields completed properly. I can't figure out what is causing this behavior however. Any help or ideas are greatly appreciated! Sorry for the length of his code snippet but I figure too much information is better than not enough in this case.
Validation rules:
$(document).ready(function() {
$("#form").validate({
errorLabelContainer: ".textbox",
keyup: false,
onfocusout: false,
onclick: false,
errorElement: "input",
errorClass: "incomplete",
rules: {
organization: {
defaultInvalid: true,
required: true,
minlength: 2
},
firstname: {
defaultInvalid: true,
required: true,
minlength: 2
},
lastname: {
defaultInvalid: true,
required: true,
minlength: 2
},
email: {
defaultInvalid: true,
required: true,
email: true
},
phone: {
defaultInvalid: true,
required: true,
minlength: 10,
},
},
});
});
Form HTML:
<div id="form">
<div id="form_title">REQUEST INFO</div>
<form id="form" name="form_container" action="#">
<!-- fields -->
<input id="organization" class="textbox" type="text" name="organization" minlength="2" value="Organization"/>
<input id="firstname" class="textbox" type="text" name="firstname" minlength="2" value="First Name"/>
<input id="lastname" class="textbox" type="text" name="lastname" minlength="2" value="Last Name"/>
<input id="email" class="textbox" type="text" name="email" value="Email"/>
<input id="phone" class="textbox" type="text" name="phone" value="Phone"/>
<!-- submit button -->
<input id="button" name="submit" class="button" type="submit" value="submit">
</form>
</div>
I'm using version 1.9 of the jQuery validation plugin.
First of all, have you added custom method
jQuery.validator.addMethod("defaultInvalid", function(value, element)
{
return !(element.value == element.defaultValue);
});
Then correct your validation JS, you have extra commas at the bottom
(document).ready(function() {
$("#form").validate({
errorLabelContainer: ".textbox",
keyup: false,
onfocusout: false,
onclick: false,
errorElement: "input",
errorClass: "incomplete",
rules: {
organization: {
defaultInvalid: true,
required: true,
minlength: 2
},
firstname: {
defaultInvalid: true,
required: true,
minlength: 2
},
lastname: {
defaultInvalid: true,
required: true,
minlength: 2
},
email: {
defaultInvalid: true,
required: true,
email: true
},
phone: {
defaultInvalid: true,
required: true,
minlength: 10
}
}
});
});
Also i suggest you to try this way:
$('#Form').validate({
onchange: false,
errorLabelContainer: $('.error-container'),
wrapper: "p",
rules: { ...//specify rules here }
});

jquery.validation required not stopping postback

I am using jQuery validation to attempt to keep a user from posting back unless he meets a couple of qualifications. But the required option doesn't seem to be keeping the form from submitting...
Here is jsFiddle with an example: jsFiddle
I double checked my jQuery code and it would seem as though it was working. jsFiddle says it valid code. So I am not sure what the hangup is?
Thanks
jQuery.validate uses names for the rules, not ids. So replace the ids with names in your input fields.
Also your form should be <form id="temp1"> and not <form id="#temp">.
Here's a link to your fixed code:
<form id="temp1">
<input type="text" name="HospitalFinNumber"/> Hospital Fin<br/>
<input type="text" name="DateOfBirth"/>Date of Birth<br/>
<input type="text" name="AdmitDate"/>Admit Date<br/>
<input type="text" name="Comment"/>Comment<br/>
<input type="submit" value="Save" class="button" id="btClick"/>
</form>
and the script:
$(document).ready(function () {
$("#temp1").validate({
rules: {
HospitalFinNumber: {
required: true,
minlength: 6
},
DateOfBirth: {
required: true
},
AdmitDate: {
required: true
},
Comment: {
required: function (element) {
return $(element).val().length < 4000;
},
maxlength: 4000
}
},
messages: {
HospitalFinNumber: 'Please Enter a Hospital Fin number',
DateOfBirth: 'Please enter a valid Date Of Birth',
AdmitDate: 'Please select an Admit Date',
Comment: 'Why dont you stop attempting to put in more than 4000 characters? Thanks...'
}
});
});

Resources