How to add validation on a dynamic textbox based from the model? - asp.net

Say I have this Jquery code:
$('.additems').click(function () {
$table = $('.item');
$table.append('<tr> <td> <input type="textbox" name="test"> </td> </tr>');
});
And I want to enable the validation from the [Required] attribute of my model who contains the property test
I tried adding the autogenerated html from the #Html.ValidationMessageFor which is
<span class="field-validation-valid" data-valmsg-for="test" data-valmsg-replace="true"></span> but it's not working.
How do I do it?

You can try different solution
$('.additems').click(function () {
$table = $('.item');
$table.append('<tr> <td> <input type="textbox" class="myReq" name="test"> </td> </tr>');
});
function foo() {
$(".myReq").each(function () {
//Your Control
});
}

Related

ASP.NET MVC - prevent submit of invalid form using jQuery unobtrusive validation

I have an ASP.NET project that automatically wires up client side validation using jQuery.Validate and the unobtrusive wrapper built by ASP.NET.
a) I definitely have the appropriate libraries: jquery.js, jquery.validate.js, & jquery.validate.unobtrusive.js
b) And the MVC rendering engine is definitely turned on (ClientValidationEnabled & UnobtrusiveJavaScriptEnabled in the appSettings section of the web.config)
Here's a trivial example where things are broken:
Model:
public class Person
{
[Required]
public string Name { get; set; }
}
Controller:
public ActionResult Edit()
{
Person p = new Person();
return View(p);
}
View:
#model validation.Models.Person
#using (Html.BeginForm()) {
#Html.ValidationSummary(false)
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
}
This generates the following client side markup:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"></script>
<form action="/Person" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
<label for="Name">Name</label>
<input data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
<input type="submit" value="Save" />
</form>
When run it will perform the client side validation, noting that some form elements are invalid, but then also post back to the server.
Why is it not preventing postback on a form with an invalid state?
The Problem
It turns out this happens when you don't include a #Html.ValidationMessageFor placeholder for a given form element.
Here's a deeper dive into where the problem occurs:
When a form submits, jquery.validate.js will call the following methods:
validate: function( options ) {
form: function() {
showErrors: function(errors) {
defaultShowErrors: function() {
showLabel: function(element, message) {
this.settings.errorPlacement(label, $(element) )
Where errorPlacement will call this method in jquery.validate.unobtrusive.js:
function onError(error, inputElement) {
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replace = $.parseJSON(container.attr("data-valmsg-replace")) !== false;
When we don't add a placeholder for the validation message, $(this).find(...) won't find anything.
Meaning container.attr("data-valmsg-replace") will return undefined
This poses a problem is when we try to call $.parseJSON on an undefined value. If an error is thrown (and not caught), JavaScript will stop dead in its tracks and never reach the final line of code in the original method (return false) which prevents the form from submitting.
The Solution
Upgrade jQuery Validate Unobtrusive
Newer versions of jQuery Validate handle this better and check for nulls before passing them to $.parseJSON
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
Add ValidationMessageFor
To address the core problem, for every input on your form, make sure to include:
#Html.ValidationMessageFor(model => model.Name)
Which will render the following client side markup
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.js"></script>
<form action="/Person" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
<label for="Name">Name</label>
<input data-val="true" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
<input type="submit" value="Save" />
</form>

Add or remove element on knockout validation error or succes

I have a konockout validation:
define([
"jquery",
"knockout",
"knockout.validation",
"inte/accdevice"
], function ($, ko, validation) {
return function (model, getzipcodeurl) {
$(function () {
ko.validation.registerExtenders();
function ViewModelprofile() {
var self = this;
self.firstName = ko.observable(model.FirstName).extend({ required: { message: errors} });
self.updating = ko.observable(true);
};
var vms = new ViewModelprofile();
vms.errors = ko.validation.group(vms);
ko.applyBindingsWithValidation(vms, document.getElementById('infosBlocEdit'), { messagesOnModified: true });
});
};
});
This is my HTML:
<input id="FirstName" name="FirstName" type="text" value="#Model.FirstName" data-bind="value: firstName" maxlength="19" />
<span class="errorMsg" data-bind="validationMessage: firstName"></span>
Actually when there is an error i show:<span class="errorMsg" data-bind="validationMessage: firstName">errors</span>
I need to personalize css on error and on success on each element validation:
On error i need to show this:<span class="invalidLine">
<span class="bble"> </span>
<span class="bbleTxt">errors</span>
</span>
and on succes:<span class="validLine"></span>
How can I do this?
If I understand the question correctly and from what I see you use knockout validation, you need something like:
<span class="invalidLine" data-bind="visible: !firstName.isValid()">
<span class="bble"> </span>
<span class="bbleTxt">errors</span>
</span>
<span class="validLine" data-bind="visible: firstName.isValid()"></span>

How to navigate to new page when click on submit button using `meteor js`

I need when click on submit or login button how to navigate to new page with same window using meteor js. please help me how to write.
when user submit the form page navigate to admindetails.html page .I am using router package and the html page and client code is below. My intention is after user login load another template in same window dynamically .Please help me.
Here is html page
<template name="body">
<div class="bgbody">
<div align="center">
<form id="login-form" action="/admindetails">
<table>
<p class="admin">Admin Login</p>
<tr>
<td><p for="username">Admin Name</p></td>
<td><input type="text" id="username" name="username" placeholder="UserName"></td>
</tr>
<tr>
<td><p for="password">Password</p></td>
<td><input type="password" id="pwd" name="password" placeholder="password"></td>
</tr>
<td></td><td><input class="btn btn-success" type="submit" value="Log In"></td>
</table>
</form>
</div>
</div>
</template>
Here is the Client code
if (Meteor.isClient)
{
Meteor.Router.add({
'/admindetails':'admindetails'
})
Template.body.events
({
'submit #login-form' : function (e,t)
{
/* template data, if any, is available in 'this'*/
if (typeof console !== 'undefined')
console.log("You pressed the button");
e.preventDefault();
/*retrieve the input field values*/
var email = t.find('#username').value
, password = t.find('#pwd').value;
console.log(email);
Meteor.loginWithPassword(email, password, function (err)
{
if (err)
{
console.log(err);
alert(err.reason);
Session.set("loginError", true);
}
else
{
console.log(" Login Success ");
Meteor.Router.to("/admindetails");
}
});
}
});
}
If you use the recommended Iron Router, you use the go method:
Router.go('/articles/example');
or:
Router.go('showArticle', {name: 'example'});
If you use the old Router, use:
Meteor.Router.to('/articles/example');
If you don't use any router, start right now. In the meantime, use the stone-age method:
window.location.href = '...';

Data binding not working but works fine in tutorial

I am new to knockout.js. I am following this tutorial. It is working fine on knockout site but not for me. Error console is also not showing any error.
Below is my code
View:
Tasks
<form data-bind="submit: addTask">
Add task: <input data-bind="value: newTaskText" placeholder="What needs to be done?" />
<button type="submit">Add</button>
</form>
<div >
<ul data-bind="foreach: tasks, visible: tasks().length > 0" id="testing">
<li>
<input type="checkbox" data-bind="checked: isDone" />
<input data-bind="value: title, disable: isDone" />
Delete
</li>
</ul>
</div>
View Model:
<script>
function Task(data) {
this.title = ko.observable(data.title);
this.isDone = ko.observable(data.isDone);
}
function TaskListViewModel() {
// Data
var self = this;
self.tasks = ko.observableArray([]);
self.newTaskText = ko.observable();
self.incompleteTasks = ko.computed(function() {
return ko.utils.arrayFilter(self.tasks(), function(task) { return !task.isDone() });
});
// Operations
self.addTask = function() {
self.tasks.push(new Task({ title: this.newTaskText() }));
self.newTaskText("");
};
self.removeTask = function(task) { self.tasks.remove(task) };
}
ko.applyBindings(new TaskListViewModel(),document.getElementById("testing"));
</script>
The problem is that the ko.applyBindings doesn't apply to all data-bind attributes. Move your "testing" id to a place where it covers all the HTML code with the relevant "data-bind" attributes.

RAZOR how to trigger an event when a user clicks on a component

I am new to RAZOR, I want to trigger an event when a user clicks on the RadioButton.
Ideally, it should dynamically show the selected value after a user clicked a RadioButton.
Questions:
How to get the selected value
How to trigger an event when a user clicked a RadioButton.
#{
Layout = "~/_SiteLayout.cshtml";
Page.Title = "Contact";
}
<div>
<table>
<tr>
<td>
#Html.RadioButton("Gender", "Male", true) Male
</td>
<td>
#Html.RadioButton("Gender", "Female", false) Female
</td>
</tr>
</table>
#Html.Label(Request["Gender"] == null ? "No Selection" : Request["Gender"])
You can not do it with Razor, What you can do is to Create Radio Button Like this and Trigger any Action using Jquery.
<input type="radio" name="sex" value="male" /> Male <br />
<input type="radio" name="sex" value="female" /> Female
You could add script (assuming you can use jQuery) on the page like:
<script type="text/javascript">
$(function () {
$(':radio[name="sex"]').change(function () {
$.ajax({
url: 'sex',
type: 'POST',
data: { sex: $('radio[name="sex"]').val() },
success: function (xhr_data) {
alert(xhr_data.someValue);
}
});
});
});
Assuming you have an action method in the same controller as the one that generated your view:
public class YourController : Controller
{
public ActionResult sex(string sex)
{
// do something awesome
return Json(new { someValue = "testing!" });
}
}
razor has abandoned event drivers model,you can use a form sheet,when you can submit the form,you can get the result in controller

Resources