jQuery dynamic validation - jquery-validate

Hi there Im trying to do a few things with jQuery validation plugin and seems stuck on one place.
Here is some code:
<script type="text/javascript">
$(document).ready(function(){
$('#myform').validate();
$('#email').rules('add', {required: true, messages: {required: 'email is required'}} );
$('#phone').rules('add', {required: true, messages: {required: 'phone is required'}} );
$('#validate').click(function(){
$('#result').text($('#myform').validate().form());
return false;
});
});
</script>
<form id="myform">
<div>email:<input type="text" id="email" /></div>
<div>phone:<input type="text" id="phone" /></div>
<div id="result"></div>
<input id="valdate" type="image" src="images/submit.png" />
</form>
As a result i keep getting a wrong error message. If i click on submit button 'phone is required' is shown near email input and 'email is required' isnt shown at all.
Whats wrong with this code ?

You might consider something like the below. It's a bit clearer to read and debug. Since you are using standard rules like "required", you don't have to specify a message unless you want something different. The rules and messages are identified by the name of the input field (e.g. email).
The errorPlacement option is where you specify the location of the messages. You don't have to include this option; the default is to append the message to the input field. But if you have layout divs or need special position for message on radio boxes, or what have you, this is the place to do it.
$(document).ready(function(){
$('#myform').validate({
rules:{
email: "required",
phone: {required:true, minlength:7}
},
messages:{ //not required as default message for "required" rule makes same text
email: "email is required",
phone: "phone is required",
},
errorPlacement: function(error, element) { //this is where to put positioning rules
error.appendTo(element.parent()); //just an example
}
});
});

OK It seems like I've found the problem.
You HAVE to add NAME attribute to elements anyway.
In my example if you add appropriate names to input elements it will work nice.

The following approach:
<script type="text/javascript">
$(function(){
$('#myform').validate({
rules: {
phone: 'required',
email: 'required'
},
messages: {
phone: 'phone is required',
email: 'email is required'
}
});
});
</script>
along with adding name attribute to each input fields, works perfectly.

Try adding the rules first and then calling $('#myform').validate()
It will not work. You have to call validate method first.
Using input names approach
I know i can do it using names as you mentioned above.
But unfortunately i will have to use ids.
content will not be constant. It will vary depending on some rules. So as a result almost each time i will have a different page.
There are will be many controls with different ids. many validation groups etc.
So using "names approach" just doesnt meet my requirements.
Any thoughts how to use $(selector).rules('add') approach??
P.S.
I've found following example http://www.coldfusionjedi.com/index.cfm/2009/2/22/Using-jQuery-to-add-form-fields--with-validation and it works pretty nice and there is nothing special in code.

Related

Using datepicker with the validation engine

I have a form which uses validation engine, but the input element that uses jquery datepicker wont display the error message or even validate as a require item. Is there a way to make both work? If not, is there another work around?
<input class="validate[required] datepicker" name="dt1" value="日付を選択" data-validation-engine="validate[required]" class="validate[required]"/>
<script>
//validate engine
$(document).ready(function(){
$("#form1").validationEngine('attach', {promptPosition : "topLeft", scroll: false});
});
//datepicker
$('.datepicker').datepicker({
constrainInput: true,
closeText: "閉じる",
prevText: "<前",
nextText: "次>",
currentText: "今日",
monthNames: [ "1月","2月","3月","4月","5月","6月",
"7月","8月","9月","10月","11月","12月" ],
monthNamesShort: [ "1月","2月","3月","4月","5月","6月",
"7月","8月","9月","10月","11月","12月" ],
dayNames: [ "日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","土曜日" ],
dayNamesShort: [ "日","月","火","水","木","金","土" ],
dayNamesMin: [ "日","月","火","水","木","金","土" ],
weekHeader: "週",
dateFormat: "yy/mm/dd",
firstDay: 0,
isRTL: false,
showMonthAfterYear: true,
yearSuffix: "年"
});
</script>
I specified the data attribute to the field as a "date", so it did finally worked.
<input class="validate[required,custom[date] datepicker" name="dt1" autocomplete="off" placeholder="日付を選択" data-validation-engine="validate[required,custom[date]" />
I had a similar issue where my datepicker was getting validated before the datepicker could assign the value, and the input would stay invalid after the datepicker assigned the value.
My issue:
I had to modify the classlist on my input, like the Jquery Validation Engine documentation describes:
class="validate[required] text-input datepicker"
I wrote this as an answer because I'm not entirely sure what happened in your case(Fernando) and your answer confused me.

Why is MVC Kendo Drop Down Not Adding Value/Input After Validation Error (Can't move past validation error)

This issue only happens in my commercial project. It does not happen in my other projects and there is no difference that I can see in set up other then my current project is running the latest update of Kendo (but others in the office are running with the latest version with no issues). Same MVC version, all using server side validation.
So this is the problem
Working scenario 1
Fill in form data
Select something in drop down
Hit Submit
Works
Working scenario 2
Fill in form data
Select something in drop down
Leave a text field unfilled
Hit Submit
Validation error on text field
Enter text
Hit submit
Works
Failing Scenario:
Fill in form data
Don't select something in drop down
Hit Submit
Validation error on drop down
Select something in drop down
Hit submit
Repeats validation error and sets drop down back to unselected
This is currently using server side validation.
When I compare one of our working kendo drop downs to the one that isn't there are two things that stand out.
The working drop down, after validation fail, when I change its selection adds a span with "k-input" that has the selected value in text form. (The broken one does not)
The broken drop down has a value field whereas the working one doesn't
The Kendo Razor from the none working project is this:
#Html.Kendo().DropDownListFor(model => model.EmployeeRecordId).OptionLabel("Please Select").DataTextField("FullName").DataValueField("EmployeeRecordId").DataSource(source => { source.Read(read => { read.Action("Get", "EmployeeRecord", new {area = "ClientArea", id = ViewBag.ClientId}); }).ServerFiltering(true); }).Events(e => { e.Change("employeeChanged"); })
The one that does work is a lot less complicated, it doesn't need to be able to update (there's a button to add a new employee on that page)
#Html.Kendo().DropDownListFor(model => model.CurrencyId).BindTo(ViewBag.Currencies).OptionLabel("Select Currency")
Below is the HTML for each, taken from the page source just after the second validation error and a value was re-selected:
Working
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="input-validation-error" data-val="true" data-val-number="The field Currency must be a number." data-val-required="The Currency field is required." id="CurrencyId" name="CurrencyId" type="text" />
<script>
jQuery(function() {
jQuery("#CurrencyId").kendoDropDownList({
"dataSource": [{
"Text": "GBP",
"Value": "1"
},
{
"Text": "EUR",
"Value": "3"
}
],
"dataTextField": "Text",
"dataValueField": "Value",
"optionLabel": "Select Currency"
});
});
</script>
<span class="field-validation-error" data-valmsg-for="CurrencyId" data-valmsg-replace="true">The Currency field is required.</span>
Not Working
<span class="field-validation-valid" data-valmsg-for="EmployeeRecordId" data-valmsg-replace="true"></span>
</div>
<div class="editor-field">
<input data-val="true" data-val-number="The field Employee Name must be a number." data-val-required="The Employee Name field is required." id="EmployeeRecordId" name="EmployeeRecordId" type="text" value="3032" />
<script>
kendo.syncReady(function() {
jQuery("#EmployeeRecordId").kendoDropDownList({
"change": employeeChanged,
"dataSource": {
"transport": {
"read": {
"url": "/ClientArea/EmployeeRecord/GetAllActiveByClientId/1003",
"data": function() {
return kendo.ui.DropDownList.requestData(jQuery("#EmployeeRecordId"));
}
},
"prefix": ""
},
"serverFiltering": true,
"filter": [],
"schema": {
"errors": "Errors"
}
},
"dataTextField": "FullName",
"dataValueField": "EmployeeRecordId",
"optionLabel": "Please Select"
});
});
</script>
<span class="field-validation-valid" data-valmsg-for="EmployeeRecordId" data-valmsg-replace="true"></span>
</div>
Does anyone have any suggestion why this might be happening.
--Update--
Another key point of the puzzle, when it is sent to the server, "EmployeeRecordId" is not included in the form collection of keys!
--UPDATE 2--
when VS is paused on the "Create" action (where i am checking the form collection) if I go back to the page, I can see that the drop down box is mysteriously not there, like its been removed via JS pre submit
After much digging I came across a similar issue.
https://www.telerik.com/forums/kendo-validation-does-not-work-the-second-time
Which although didn't provide me an answer for why the server side is failing. It did lead me to how to get client side validation working for kendo drop downs. Which as it happens before sever side seems to stop the error ever happening.
To enable client side validation on kendo drop downs you need to add this code to the very bottom of your page (so the very bottom of your layout file)
<script type="text/javascript">
$.validator.setDefaults({
ignore: ""
});
</script>
You will need to enable the usual mvc client side validation with the jquery scripts.
I'm hesitant to mark this as best answer as it doesn't answer the question of why this is happening at all but I have posted it to help others with the same problem :)
Not the ideal solution.
But you'll have to add following code for every form submission with validations.
Found the solution from the Kendo UI official Support page. It looks more like a bug.
To get it working, you can add the following code at the bottom of you page. (After the page is loaded)
$(document).ready(function () {
$(".k-widget").removeClass("input-validation-error");
});

Custom validation message for my checkbox

I have below terms and condition checkbox created for a form
<input type="checkbox" name="checkbox" id="checkbox_id" class="checkbox required-entry" value="value">
I am getting "this is required field" as validation message but I want to change it to "Please check our terms and condition". Please suggest.
['validate-firstname', 'First name is required field.', function(v) {
return !Validation.get('IsEmpty').test(v);
}],
modify or add one rule in validation js like above code.

jQuery Validate rules wont apply

I am trying to use jQuery validate for a form.
I have added
<script type="text/javascript" src="Scripts/jquery.validate.js"></script>
My form:
<form id="Main">
<asp:TextBox ID="Box" name="box" required runat="server"
</form>
At bottom of page
$('#Main').validate();
This works. Which is great. But if I remove the required attr and try say
$('#Main').validate({rules:{box:{required:true}}});
This does not work. For the life of me i cant figure out what I am doing wrong.
In the end I need that input to be required and numeric.
I tried adding 'number' as an attribute but that didn't work either.
some guidance would be great.
Thanks.
There are a number of validation plugins available, after some searching I think I found the plugin you're using based on the usage here.
I created a fiddle to demo how to make a field required and numeric ... click here for fiddle.
Based on the code you provided, it looks like you're only including the base validate.js library. You need to be sure to include the css file, and if you want to use some out of the box validations, such as number validations then you will also need to include the additional-methods.js file. All these files can be found HERE.
Here is the code from the fiddle above..
<form id="myform">
<input type="text" class="box" id="box" name="box">
<br/>
<input id="submit" type="submit" value="Validate!">
</form>
$(document).ready(function()
{
$("#myform" ).validate(
{
rules:
{
box:
{
required: true,
number: true
}
}
});
});

How to prepopulate tokenput with values found in database

I am using the tokeninput control found here at http://loopj.com/jquery-tokeninput/ - its quite popular I believe.
I have the following code that fills the input box nicely with author names - but I want to prepopulate the control with values found in the database when the user is in an EDIT session i.e. to find authors that have been found for that record already (looks something like this):
Here's the code:
$("#authorlist").tokenInput('/author/getauthors/', {
hintText: "Enter surname",
searchingText: "Searching...",
preventDuplicates: true,
allowCustomEntry: true,
highlightDuplicates: false,
tokenDelimiter: "*",
theme: "facebook"
// prePopulate: [{"id": 5016, "name": "Test 1" }]
});
Obviously this already gets a full list of authors (/author/getauthors/) - but it needs to prepopulate from that list too, with authors already found that record - and thats the bit I can't seem to figure out.
I can see that that you can use prePopulate in the javascript (I've commented it out) and I have the found author values in my Edit.cshtml i.e.
#foreach(var item in Model.AUTHORs.Select(model => new { model} ))
{
<div type="hidden" id="authorHidden" > #item.model.FULL_NAME</div>
}
So it's just a case of putting those values in some kind of json format and getting the tokeninput control to populate them ready for when the form is loaded and shown to the user.
Other code for displaying the tokeninput control in Edit.cshtml is:
<div class="editor-label">Authors</div>
<div class="authors">
<div class="editor-field">
<input type="text" id="authorlist" name="tiAuthors" />
</div>
</div>
Any help or pointers are much appreciated.
You could use an HTML5 data-* attribute on your input inside the view to put the list of authors that you want to be prepopulated:
<input type="text" id="authorlist" name="tiAuthors" data-authors="#Json.Encode(Model.AUTHORs.Select(a => new { id = a.AuthorId, name = a.AuthorName })))" />
and then:
$('#authorlist').tokenInput('/author/getauthors/', {
hintText: 'Enter surname',
searchingText: 'Searching...',
preventDuplicates: true,
allowCustomEntry: true,
highlightDuplicates: false,
tokenDelimiter: '*',
theme: 'facebook',
prePopulate: $('#authorlist').data('authors')
});

Resources