.k-state-error is not being applied to Kendo Date Picker - kendo-ui

I am using Model validation and k-state-error css class is not being applied to it in case validation fails. what else i can do to add this class to my datepicker
function onChange(e) {
if (e.date == undefined) {
var item = $(this).find('.k-picker-wrap');
$(item).addClass("k-state-error");
// $(e).css("border-color", "red");
}
}
using this code to add class but it's not working. Perhaps jquery selector is not right

From your code seems that you are trying to implement a validation that checks that the date is required. Why not implementing it as:
HTML:
<input id="date" required/>
JavaScript:
$("#date")
.kendoDatePicker({})
.kendoValidator({
validateOnBlur: true,
messages : {
required : "My custom required message"
}
});

Related

Angular 5 - Reactive forms doesn't validate form on submit

I have a simple form as below:
some.component.html
<form class="example-form" novalidate (ngSubmit)="onSubmit()" autocomplete="off" [formGroup]="testform">
<input type="text" formControlName="name" class="form-control" placeholder="Enter name" required/>
<app-show-errors [control]="claimform.controls.name"></app-show-errors>
<button type="submit" (click)="onSubmit()">Next</button>
</form>
some.component.ts
ngOnInit() {
this.testform= new FormGroup({
name: new FormControl('', { validators: Validators.required})
}, {updateOn: 'submit'});
}
onSubmit() {
if (this.testform.valid) {
alert('saving data');
} else {
this._validationService.validateAllFormFields(this.testform);
}
}
validationService.ts
validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
Reference
Problem
The form will validate on submit if left blank, but even after filling the value when I check this.testform.valid it returns false. But if I remove updateOn:'submit' on form then it validates on blur of input control and when value is entered it validates form return true. Not sure if updateOn is working fine or not or whether I've implemented this in a proper way. Could someone point me in the right direction.
in your HTML you have two calls to onSubmit() function, from submit button:
<button type="submit" (click)="onSubmit()">Next</button>
and from the form:
<form class="example-form"
ovalidate
(ngSubmit)="onSubmit()"
autocomplete="off"
[formGroup]="testform">
The first call to be triggered is the button's trigger, which actually does nothing in terms of updating your reactive form, since you set FormGroup's option to {updateOn: 'submit'}. The second call to be triggered is the form's trigger, which does actual form update.
Here is FormGroup directive config:
#Directive({
selector: '[formGroup]',
providers: [formDirectiveProvider],
host: {'(submit)': 'onSubmit($event)', '(reset)': 'onReset()'},
exportAs: 'ngForm'
})
as we can see in host property DOM form's submit (triggered by hitting ENTER while focused within form or clicking form's submit button) will call onSubmit() function:
onSubmit($event: Event): boolean {
(this as{submitted: boolean}).submitted = true;
syncPendingControls(this.form, this.directives);
this.ngSubmit.emit($event);
return false;
}
which then will call syncPendingControls() function:
export function syncPendingControls(form: FormGroup, directives: NgControl[]): void {
form._syncPendingControls();
directives.forEach(dir => {
const control = dir.control as FormControl;
if (control.updateOn === 'submit' && control._pendingChange) {
dir.viewToModelUpdate(control._pendingValue);
control._pendingChange = false;
}
});
}
which updates a model at last.
So, in your case, just remove (click)="onSubmit()" from the submit button:
<button type="submit">Next</button>
also you do not need required DOM element property on your input, since you set it using Reactive Forms API validators: Validators.required and since you set your form to novalidate which cancels HTML5 form validation.

AngularJS Form Validation inside an ng-repeat

So I am trying to validate the input of one item inside of an ng-repeat. For examples sake lets say that I have 5 items (1,2,3,4,5) and I only want to validate the form if the 4th item is selected.
I have used ng-pattern before to validate forms, but not one that had a dropdown menu to select item.name
I have included the regex I would like the 4th item to be validated with inside the ng-pattern.
<div>
<select name="name" ng-model="item.name" ng-options="item for item in items" required></select>
</div>
<div>
<input name="results" type="text" ng-model="item.results" ng-pattern="/^\d\d\d\/\d\d\d/" required>
</div>
Any suggestions as to the correct way to validate this situation would be greatly appreciated. I have thought about creating a directive to validate this, but that feels like is an overly complicated solution to this since I would not use the directive more than once in this app.
//////////////////////////////////////////////////
It wouldn't let me answer my own question so here is the answer I figured out.
What I ended up having to do was use ng-pattern and pass it a function.
<input name="results" type="text" ng-model="vital.results" ng-pattern="vitalRegEx()" required>
Here is the controller code
$scope.item4RegEx = /^\d{2,3}\/\d{2,3}$/;
$scope.itemRegEx = function() {
if($scope.item && $scope.item.name === "fourth item")
return $scope.item4RegEx;
else return (/^$/);
};
or else...
add ng-change directive on the select dropdown which calls a Controller method and that controller method sets a flag whether to validate form or not.
eg.
<select ng-change="checkIfFormShouldbeValidated()" ng-model="item.name"></select>
// Inside controller
$scope.checkIfFromShouldBeValidated = function(){
if( $scope.item.name == 4th Item ) $scope.shouldValidate = true;
else $scope.shouldValidate = false;
};
$scope.formSubmit = function(){
if(($scope.shouldValidate && form.$valid) || (!$scope.shouldValidate)){
// Submit Form
}
};
See if it helps.
I wrote this recursive function inside my controller to check the validity of all child scopes.
function allValid(scope) {
var valid = true;
if (scope.$$childHead) {
valid = valid && allValid(scope.$$childHead);
}
if (scope.$$nextSibling) {
valid = valid && allValid(scope.$$nextSibling);
}
if (scope.scorePlannerForm) {
valid = valid && scope.myForm.$valid;
}
return valid;
}
Then in my controller I check this with the controller scope.
function formSubmit() {
if (allValid($scope)) {
// perform save
}
}

ASP.NET MVC 3 - Custom client side validation not working

I'm trying to implement a custom client side validation, but it is not working. I'm basing myself on the article on Codeproject http://www.codeproject.com/Articles/275056/Custom-Client-Side-Validation-in-ASP-NET-MVC3
I also looked here on SO, but I think I'm implementing it in the correct manner, but I'm overlooking something.
My goal is to validate a date (required, date format and not earlier than another date on the form). The first two can be done with data annotations, the last I have to do with custom validation.
I have on my base class some dataannotations (ClassLibrary is in VB.NET):
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
<MetadataType(GetType(CM_CONTRACTVALIDATIONData))>
Partial Public Class CM_CONTRACTACTIVATION
'...
End Class
Public Class CM_CONTRACTVALIDATIONdata
'...
<DataType(DataType.Date)>
<Required()>
Public Property TakeBackDeviceWhen
'..
End Class
In the javascript file I have added the custom method:
//validation
$.validator.addMethod("checkPickupDate", function (value, element) {
return false;
});
$("#form").validate({
rules: {
TakeBackDeviceWhen: {
checkPickupDate: true
}
},
messages: {
TakeBackDeviceWhen: {
checkPickupDate: "Test"
}
}
}
);
My chtml file is as follow:
#Html.TextBox("TakeBackDeviceWhen", Model.TakeBackDeviceWhen.HasValue ? Model.TakeBackDeviceWhen.Value.ToShortDateString() : "", new { style = "Width: 200px" })
The resulting HTML is as follow:
<input id="TakeBackDeviceWhen" class="hasDatepicker" type="text" value="" style="Width: 200px" name="TakeBackDeviceWhen" data-val-required="The TakeBackDeviceWhen field is required." data-val="true">
It seems that neither my type validation and my custom validation isn't implemented.
What is going wrong?
OK, solved it. I hope :-)
What did I learned today:
(1) Don't use EditorFor: when you scaffold it from a MVC template, input fields are generated to EditorFor, it seems that you can't add custom unobtrusive validation tags. So, I was trying to get this fixed, untill I changed it to TextBoxFor.
(2) You can add custom validation methods in jQuery, but you can't mix them with unobtrusive validation. After adding a custom method, you have to also add it to the unobtrusive adapters. And don't forget to add jQuery on the bottom :-s (I got this from jQuery.validator.unobtrusive.adapters.addMinMax round trips, doesn't work in MVC3)
$(function () {
$.validator.addMethod("checkpickupdate", function (value, element) {
if (value == "20/09/2012") {
return false;
} else {
return true;
}
});
$.validator.unobtrusive.adapters.addBool("checkpickupdate");
} (jQuery));
(3) Add validation tags to the input field in the htmlAttributes:
#Html.TextBox("TakeBackDeviceWhen", Model.TakeBackDeviceWhen.HasValue ? Model.TakeBackDeviceWhen.Value.ToShortDateString() : "",
new {
style = "Width: 200px",
data_val = "true",
data_val_required = "verplicht!",
data_val_date = "moet datum zijn",
data_val_checkpickupdate = "wow"
})
(4) Datatype data annotations will not enforce a validation. You have to add it like in (3). You can add a custom ValidationAttribute like (for server side validation):
public class MustBeDateAttribute : ValidationAttribute {
public override bool IsValid(object value) {
try
{
DateTime dte = DateTime.Parse(value.ToString());
return true;
}
catch (Exception)
{
return false;
throw;
}
}
}
And this is the resulting html output:
<input type="text" value="" style="Width: 200px" name="TakeBackDeviceWhen" id="TakeBackDeviceWhen" data-val-required="required!" data-val-date="has to be a date" data-val-checkpickupdate="custom error" data-val="true" class="hasDatepicker valid">
As I'm using my ClassLibrary in different projects, I'm now going to try to seperate the dataannotations meta data from the class library (maybe with dependency resolver).

Issue with validation on Razor View in MVC

I am building wizard step demo application with MVC3 and using razor view engine as begineer level.
I came across on problem with validation when hide & show control through javascript.
Please look my code section as per below
<div class="editor-field">
#Html.EditorFor(model => model.CheckName2)
#Html.ValidationMessageFor(model => model.CheckName2)
</div>
my javascript function as per below, hide & show on some condition
// attach nextStep button handler
$("#next-step").click(function () {
var $step = $(".wizard-step:visible"); // get current step
//check if URL2 is having any content
var val = $("#URL2").val();
if (val == "") {
$("#CheckName2").hide();
//want to remove validation here
}
else {
$("#CheckName2").show();
//want to add validation here
}
var validator = $("form").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
How can i handle validation here?
thanks in advance.
Force validation of your form with $("#IdOfFormYouEdit").validate(); or $("#IdOfTextbox").validate(); to validate only one element.
This is possible if you have put validation attributes on your view model classes. If you don't you can add validation on an element by adding the data-val attributes. For example:
<input type="text" data-val="true" data-val-number="The field someField must be a number." data-val-required="SourceId required" />

Conditional validation in MVC3

In MVC3, there are a way to add or stop validation in a field depending on the value of a drop-drown list with JQuery? I have been trying with Fluent Validation, but with no luck.
Are you using unobtrusive validation? Is so, look at the html and you will see that there are some html5 attributes on your input, something like this:
<input name="product" id="product" data-val="true" data-val-required="Product is required" />
I suppose you could use jQuery to remove the data-val attribute and then the jQuery Validator will skip this item.
$("#product").data("val", false);
Well, that's my guess, try it yourself.
you should use jQuery AddClass Rules
Create jQuery Class
$.validator.addClassRules({
Req: {
required: true
}
});
Validate the Filed by checking the selected value
$("#Selector").blur(function () {
var Val= $("#Selector").val();
if (Val == "Compare to the String") {
$("#Selector").addClass("Req");
}
else {
$("#Selector").removeClass("Req");
}
});

Resources