asp.net mvc - How to validate Date in ClientSide using FluentValidation? -


question

the below code working fine server side , not client side. why ?


when submit form, control goes beavaliddate function check date valid or not. there way validate date without going server using fluent validation?

scripts

<script src="jquery-1.7.1.min.js" type="text/javascript"></script> <script src="jquery.validate.js" type="text/javascript"></script> <script src="jquery.validate.unobtrusive.js" type="text/javascript"></script> 

model

public class personvalidator : abstractvalidator<person> {     public personvalidator()     {         rulefor(x => x.fromdate)             .notempty()             .withmessage("date required!")             .must(beavaliddate)             .withmessage("invalid date");     }      private bool beavaliddate(string value)     {         datetime date;         return datetime.tryparse(value, out date);     } } 

controller

public class personcontroller : controller {     public actionresult index()     {        return view(new person { fromdate = datetime.now.adddays(2).tostring()});     }      [httppost]     public actionresult index(person p)     {         return view(p);     } } 

view

@using (html.beginform("index", "person", formmethod.post)) {        @html.labelfor(x => x.fromdate)     @html.editorfor(x => x.fromdate)     @html.validationmessagefor(x => x.fromdate)      <input type="submit" name="submit" value="submit" /> } 

trick using greater or equal validator. works me.

global.asax - application start event

fluentvalidationmodelvalidatorprovider.configure(x => {     x.add(typeof(greaterthanorequalvalidator),              (metadata, context, rule, validator) =>                  new lessthanorequaltofluentvalidationpropertyvalidator                 (                     metadata, context, rule, validator                 )             ); }); 

model

[validator(typeof(myviewmodelvalidator))] public class myviewmodel {     [display(name = "start date")]     [displayformat(dataformatstring = "{0:yyyy-mm-dd}",                                                    applyformatineditmode = true)]     public datetime startdate { get; set; }      [displayformat(dataformatstring = "{0:yyyy-mm-dd}",                                                    applyformatineditmode = true)]     public datetime datetocompareagainst { get; set; } } 

rule

public class myviewmodelvalidator : abstractvalidator<myviewmodel> {     public myviewmodelvalidator()     {         rulefor(x => x.startdate)             .greaterthanorequalto(x => x.datetocompareagainst)             .withmessage("invalid start date");     } } 

fluentvalidationpropertyvalidator

public class greaterthenorequalto : fluentvalidationpropertyvalidator {     public greaterthenorequalto(modelmetadata metadata,                                  controllercontext controllercontext,                                  propertyrule rule,                                  ipropertyvalidator validator)         : base(metadata, controllercontext, rule, validator)     {     }      public override ienumerable<modelclientvalidationrule>                                                      getclientvalidationrules()     {         if (!this.shouldgenerateclientsiderules())         {             yield break;         }          var validator = validator greaterthanorequalvalidator;          var errormessage = new messageformatter()             .appendpropertyname(this.rule.getdisplayname())             .buildmessage(validator.errormessagesource.getstring());          var rule = new modelclientvalidationrule{             errormessage = errormessage,             validationtype = "greaterthanorequaldate"};         rule.validationparameters["other"] =              compareattribute.formatpropertyforclientvalidation(                 validator.membertocompare.name);         yield return rule;     } } 

controller action method

public actionresult index() {     var model = new myviewmodel     {         startdate = datetime.now.adddays(2),         datetocompareagainst = default(datetime)  //default date     };     return view(model); } [httppost] public actionresult index(practise.areas.fluentval.models.myviewmodel p) {     return view(p); } 

view

@using (html.beginform("index", "person", formmethod.post,                                                  new { id = "formsubmit" })) {        @html.hidden("datetocompareagainst", model.datetocompareagainst);           @html.labelfor(x => x.startdate)     @html.editorfor(x => x.startdate)     @html.validationmessagefor(x => x.startdate)     <button type="submit">         ok</button> } 

script

<script src="jquery-1.4.1.min.js" type="text/javascript"></script> <script src="jquery.validate.js" type="text/javascript"></script> <script src="jquery.validate.unobtrusive.js" type="text/javascript"></script> <script type="text/javascript">     (function ($) {         $.validator.unobtrusive.adapters.add('greaterthanorequaldate',                                               ['other'], function (options) {             var getmodelprefix = function (fieldname) {                 return fieldname.substr(0, fieldname.lastindexof(".") + 1);             };              var appendmodelprefix = function (value, prefix) {                 if (value.indexof("*.") === 0) {                     value = value.replace("*.", prefix);                 }                 return value;             }              var prefix          = getmodelprefix(options.element.name),                 other           = options.params.other,                 fullothername   = appendmodelprefix(other, prefix),             element = $(options.form).find(":input[name=" + fullothername +                                                          "]")[0];              options.rules['greaterthanorequaldate'] = element;             if (options.message != null) {                 options.messages['greaterthanorequaldate'] = options.message;             }         }); 

        $.validator.addmethod('greaterthanorequaldate',                                 function (value, element, params) {             var date = new date(value);             var datetocompareagainst = new date($(params).val());              if (isnan(date.gettime()) || isnan(datetocompareagainst.gettime())) {                 return false;             }             return date >= datetocompareagainst;         });      })(jquery); </script> 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -