knockout-validation: render html tag in message - knockout-validation

In the MVC + knockout project client wants to have a link in validation message.
JS file:
ko.validation.rules['standardCharsValidation'] = {
validator: function (val, params) {
return /^$|^[a-zA-Z0-9 \&,.\\\/;:\[\]\-\(\)\_\!\'\`]+$/.test(val);
},
message: 'Error: Invalid text entered, please see <a class=\'CssLinkClass\' target=\'_blank\' href=\'' + Controllers.HomeHelp + '\'>Help</a>'
};
And in view:
<input type="text" id="Postcode" class="input-xsmall" name="Postcode" id="Postcode" data-bind="value: Postcode, valueUpdate: 'afterkeydown'"/>
<label class="error" style="text-align: left;" data-bind="validationMessage: Postcode"></label>
The results are as follow
Error: Invalid text entered, please see <a class='CssLinkClass' target='_blank' href='/Home/Help'>Help</a>
Is there any way to make it render that element properly?

Using a custom validation message template can give you the desired result. This particular implementation injects a custom message in the middle "Error: <custom message>, please see <help link>"
http://jsfiddle.net/vmmbhwes/1/
<script type="text/html" id="helpLinkTemplate">
<span data-bind="if: field.isModified() && !field.isValid()">
Error: <span data-bind='validationMessage: field'></span>, please see
<a class='' target=\'_blank\' href="http://stackoverflow.com">Help</a>
</span>
</script>
By selectively wrapping your input fields with a custom validation template, you can apply your custom templates as needed
<div data-bind="validationOptions: {messageTemplate: 'helpLinkTemplate'}">
UserName (custom template):<br/>
<input data-bind="value: name" />
</div>
Number (standard template):<br/>
<input data-bind="value: number" />

Related

Html.ValidationMessageFor not displaying at all

I have the following form:
<form action="~/buy-online" method="get" class="buy-online-form clearfix" autocomplete="off" id="buy-online-search">
<div class="infield-holder clearfix">
#Html.LabelFor(m => m.CustomerPostcode, new { #class = "infield" })
#Html.TextBoxFor(m => m.CustomerPostcode, new { #class = "textbox" })
<input type="submit" value="Buy Online" id="find-retailer-button" class="button" />
</div>
</form>
#Html.ValidationMessageFor(m => m.CustomerPostcode)
Which works fine and will display an error message when submitted without jQuery, but when I add the jQuery validate scripts (v 1.11.1):
<script src="/scripts/jquery.validate.js"></script>
<script src="/scripts/jquery.validate.unobtrusive.js"></script>
It stops the form submitting but doesn't display the error message
My property is marked like so:
[DisplayName("Enter your full postcode")]
[Required(ErrorMessage = "Please enter your full postcode")]
public string CustomerPostcode { get; set; }
And the html renders like this:
<input class="textbox" data-val="true" data-val-required="Please enter your full postcode" id="CustomerPostcode" name="CustomerPostcode" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="CustomerPostcode" data-valmsg-replace="true"></span>
If I inspect the input when I hit submit it is adding the class input-validation-error to the textbox but just not updating the validation message.
All the posts that I have checked on this problem just say to include the scripts so I'm at a loss as to why the message is not showing.
I've even tried adding the jquery.unobtrusive-ajax.js script but that didn't seem to do anything either. Any help would be appreciated, thanks.
You need to include the #Html.ValidationMessageFor(m => m.CustomerPostcode) within the form tags for jquery.validate.unobtrusive to work.

How to fix conflict with jQuery UI and jQuery? Datepicker giving error

I am trying to use the jQuery datepicker for a form on a site that uses jQuery 1.3.2 but it's not working. I have to reference a newer jQuery library for some of my form functionality, and also the jQuery ui for datepicker to work. I have used noConflict for the newer jquery library but it's still not working. I get Uncaught TypeError: Cannot read property 'document' of null in the console. Updating/removing the 1.3.2 reference is not an option.
Here is my fiddle, which works. but i get the error above in Chrome (not FF) and the datepicker will not work on my site. http://jsfiddle.net/pnA33/
Can anyone help? It works locally but not on the server (which is a dev enviornment so I can't share a link). I found this but as I am relatively new to jQuery it is over my head.
jQuery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script type="text/javascript">
var jQuery_1_9_1 = jQuery.noConflict(true);
jQuery_1_9_1(document).ready(function() {
jQuery_1_9_1( "#datepicker" ).datepicker({ minDate: -1, maxDate: "+24D" });
jQuery_1_9_1('#pancettaForm').change(function () {
jQuery_1_9_1('.address,#new-ship-date').hide();
if (jQuery_1_9_1('#ship-address').prop('checked')) {
jQuery_1_9_1('.address').show();
}
else if (jQuery_1_9_1('#ship-date').prop('checked')) {
jQuery_1_9_1('#new-ship-date').show();
}
else if (jQuery_1_9_1('#ship-both').prop('checked')) {
jQuery_1_9_1('.address, #new-ship-date').show();
}
});
});
function validateForm()
{
var x=document.forms["pancettaForm"]["order-number"].value;
if (x==null || x=="")
{
alert("Please provide your order number from the confirmation email sent immediately after placing your order.");
return false;
}
}
</script>
HTML:
<form name="pancettaForm" method="post" action="http://lizlantz.com/lcform.php" id="pancettaForm" onsubmit="return validateForm()">
<input type="hidden" value="Pancetta Order Update" name="subject">
<input type="hidden" value="cookware/partners_10151_-1_20002" name="redirect">
<ol>
<li>
<label for="update-ship">I'd like to:</label>
<input id="ship-address" name="update-ship" type="radio" value="update-ship-address"/> Have pancetta shipped to a different address than my skillet<br />
<input id="ship-date" name="update-ship" type="radio" value="update-ship-date" /> Have pancetta shipped sooner than June 14, 2013 <br />
<input id="ship-both" name="update-ship" type="radio" value="update-both" /> Make changes to both the shipping address and shipping date
</li>
<li>
<label for="order-number"><em>*</em>Order Number (available in order confirmation email):</label>
<input type="text" name="order-number">
</li>
<li>
<label for="full-name"><em>*</em>Recipient Full Name:</label>
<input type="text" name="full-name">
</li>
<li class="address" style="display: none;">
<label for="address">
<em>*</em>Address
</label>
<input type="text" name="address">
<label for="address2">
Address Line 2
</label>
<input type="text" name="address2">
</li>
<li class="address" style="display: none;">
<label for="city">
<em>*</em>City
</label>
<input type="text" name="city">
<label for="state">
<em>*</em>State
</label>
<select name="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
</select>
<label for="zip">
<em>*</em>Zip Code
</label>
<input type="text" name="zip">
</li>
<li id="new-ship-date" style="display: none;">
<em>*</em><label for="updated-ship-date">New Ship Date:</label>
<input type="text" id="datepicker" name="updated-ship-date" value="Update Your Ship Date" />
</li>
<li>
<label for="phone">
<em>*</em>Phone (for delivery questions)
</label>
<input type="text" name="phone">
</li>
</ol>
<input type="submit" id="button" name="submit" value="Update Pancetta">
</form>
Ah ha! You actually cannot run two versions of jQuery on the same document instance at one time...hence the issue here. This solution comes directly from Splendìd Angst's answer in this thread Can I use multiple versions of jQuery on the same page?
Basically you must declare your noConflict version prior to entering the document "main loop" I suppose you can call it.
Declare your noConflict variable outside the document.ready call...use the standard $(document).ready() syntax, then use (and ONLY use) your noconflict variable within the ready closure. That should do it.
I haven't tested this mind you but it makes sense and it won't take you much tweaking of your code to try it out.
TIL something new about jQuery :)

unable to display the validation messages from #Html.ValidationSummary() in MVC view

I have a fairly simple form created in a partial view and loading the form on a jquery dialog. The view is tightly bound to a model. When the user clicks on the submit button with out entering any inputs, I need to show the validation messages.
<div>
<form method="post" enctype="multipart/form-data" id="ssimForm" action="Home/ProcessUploadedFile"
onsubmit="return false;">
<div>
<h3>
Select the file to be uploaded :</h3>
<span>
<input type="file" name="UploadFileName" id="UploadFileName" /></span>
</div>
<div>
<h3>
Select the date range :</h3>
<span class="uslabel">From Date(MM/dd/yyyy): </span>
<input class="usdate" id="usfromdate" name="StartDate" type="date" />
<span class="uslabel">To Date(MM/dd/yyyy): </span>
<input class="usdate" id="ustodate" name="EndDate" type="date" />
</div>
<div>
<br />
<input type="submit" id="submitButton" name="submitButton" value="Process File" />
</div>
#Html.ValidationSummary()
<div class="message-success">
<span>#ViewBag.Confirmation</span>
</div>
<div class="message-error">
<span>#ViewBag.Error</span>
</div>
</form>
</div>
Now comes the actual problem. when I submit the form I am able to see the validationSummary object populated with the messages, but they are not getting rendered on the screen.
I am able to see the messages if I replace the content of the dialog with the response from the jquery ajax call, that fetches the entire view from the server side. I do not want to take this approach as I beleive this is not the correct way to return validation summary in MVC.
Am I missing something? Any help is appreciated.
I don't know why you don't have the #using (Html.BeginForm()) { } block.
Here is my blog post for a quick and easy way to set up Validation Summary + Unobtrusive Validation for MVC3+.
http://geekswithblogs.net/stun/archive/2011/01/28/aspnet-mvc-3-client-side-validation-summary-with-jquery-validation-unobtrusive-javascript.aspx

Why am I getting this Javascript HIERARCHY_REQUEST_ERR with jQuery Mobile and Razor?

Dazed and confused here... The field in question is a boolean, and I want the UI to be a checkbox (or a yes/no or on/off jQuery slider). Each time I try to add in this checkbox input, I end up getting a
Microsoft JScript runtime error: DOM Exception: HIERARCHY_REQUEST_ERR (3)
error.
Here's the HTML+Razor
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
#Html.TextBoxFor(model => model.HandicapSession.WinByTwo, new { #type="checkbox" })
<label for="WinByTwo">Win By Two?</label>
</fieldset>
</div>
Here's the generated HTML:
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
<input data-val="true" data-val-required="The WinByTwo field is required." id="HandicapSession_WinByTwo" name="HandicapSession.WinByTwo" type="checkbox" value="False" />
<label for="WinByTwo">Win By Two?</label>
</fieldset>
</div>
Apparently this error occurs when there are conflicting or overlapping id's as jQuery Mobile creates its checkbox widget
$.widget( "mobile.checkboxradio", $.mobile.widget, { ...etc...
But how do I use the HTML and/or razor to make a simple checkbox work in jQuery Mobile?
If the problem with jQuery Mobile really is duplicate names for the HTML tags, then you'll have to render your own input type=checkbox tag in HTML, as the ASP.NET MVC Html.CheckBoxFor helper method will render an input type=hidden tag with a duplicate name value. See this post for a discussion.
The hidden form tag is there because if you submit an unchecked checkbox to the server, the form value for that field isn't included. So a hidden input tag is included with value=false so that if the checkbox is unchecked, the value false is still submitted. The model binding process in MVC will filter out the duplicate form values for you, but if you're having a client-side problem with the duplicate name attributes, you'll have to render your own checkbox and label in HTML, then handle the fact that no value will be submitted for the HandicapSession.WinByTwo property when the box is unchecked. If no other property for HandicapSession is submitted, then that whole object will be null.
So, you can manually create the checkbox input and still load the checked and value attributes from your model, as desired, but you can run into model binding problems where the value for WinByTwo will still be false even when the box is checked.
Note also that the for attribute on your label doesn't match the ID of the checkbox in your sample. You need the full HandicapSession_WinByTwo.
The following manually creates the input tags:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js"></script>
<div data-role="page">
<div data-role="content">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
<input type="checkbox" id="HandicapSession_WinByTwo" name="HandicapSession.WinByTwo" #(Model.HandicapSession.WinByTwo ? "checked=checked" : "") value="#(Model.HandicapSession.WinByTwo.ToString().ToLower())" />
<label for="HandicapSession_WinByTwo">Win By Two?</label>
</fieldset>
</div>
</div>
</div>
The HTML output is as follows for a checked checkbox on load:
<div data-role="page">
<div data-role="content">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
<input type="checkbox" id="HandicapSession_WinByTwo" name="HandicapSession.WinByTwo" checked=checked value="true" />
<label for="HandicapSession_WinByTwo">Win By Two?</label>
</fieldset>
</div>
</div>
</div>
The best would be just to use the MVC helper methods, so I'm not sure if you'd tried the following. The default Html.CheckBoxFor and Html.LabelFor helper methods work with jQuery Mobile 1.0a4.1 or 1.1.0 just fine. The following works for me:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.js"></script>
<div data-role="page">
<div data-role="content">
#using (Html.BeginForm())
{
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
#Html.CheckBoxFor(m => m.HandicapSession.WinByTwo)
#Html.LabelFor(m => m.HandicapSession.WinByTwo, "Win By Two?")
<input type="submit" id="SubmitForm" value="submit" />
</fieldset>
</div>
}
</div>
</div>
This produces the HTML output:
<div data-role="page">
<div data-role="content">
<form action="/Mobile/Mobile" method="post">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>End Game:</legend>
<input checked="checked" data-val="true" data-val-required="The WinByTwo field is required." id="HandicapSession_WinByTwo" name="HandicapSession.WinByTwo" type="checkbox" value="true" />
<input name="HandicapSession.WinByTwo" type="hidden" value="false" />
<label for="HandicapSession_WinByTwo">Win By Two?</label>
<input type="submit" id="SubmitForm" value="submit" />
</fieldset>
</div>
</form>
</div>
</div>
Fix might be pretty simple.
Choice 1: Go scorched earth and turn off Ajax based navigation. This will ensure that unique IDs stay unique. This will ensure that you never encounter this issue again. Only downside is that you lose the pretty little transitions from page to page (someone call the whambulance). You can do this by setting up a global configuration script...
script src="jquery.js"
script src="custom-scripting.js"
script src="jquery-mobile.js"
inside that you'll override the ajax settings to disable them...
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
Choice 2: Call pages that are going to require this uniqueness with a link that has an attribute of rel='external' or target='_black' which will accomplish the same thing without disabling all ajax based navigation. If you are reaching the page as a results of a form post, you can use data-ajax='false' on the form tag to accomplish a clean load.

How do you customize Ruby on Rails validation errors?

Currently when there is a validation error, a div with class="field_with_errors" gets rendered in my form:
<form method="post" action="/users" accept-charset="UTF-8">
<div class="field_with_errors">
<input id="user_email" type="text" value="tom#test.com" name="user[email]">
</div>
<input id="user_password" type="password" value="mypass" size="30" name="user[password]">
<input id="user_submit" type="submit" value="Submit" name="commit">
</form>
Without the use of an additional gem and in a Rails 3 environment, is there a way to modify how the validation error is rendered? For example, I want the validation error div to be rendered after the input tag with the error:
<input id="user_email" type="text" value="tom#test.com" name="user[email]"><div class="field_with_errors"></div>
Also, is there a way to render a specific error? If it was an email error, then render the div after the input textbox and produce a "Re-enter your email" message.
(Most of the searches I have done so far use gems as the solution.)
1.You can remove the field_with_errors wrapper by overriding ActionView::Base.field_error_proc.It can be done by putting this in your config/application.rb:
config.action_view.field_error_proc = Proc.new { |html_tag, instance| "#{html_tag}".html_safe }
Refer
Rails 3: "field-with-errors" wrapper changes the page appearance. How to avoid this?
2.You can display error message on specific field.
<input id="user_email" type="text" value="tom#test.com" name="user[email]">
<% if #user.errors.on(:email).present? %>
<span class="error">Re-enter your email(or)<%= #user.errors.on(:email) %></span>
<% end %>
Then in your CSS
.error {
color: red;
}

Resources