locked
clientside validation with custom validators RRS feed

  • Question

  • User65893105 posted

    Ive created a custom validator to check if a date entered is within a specific range.  this works fine server side, but i cant get it to work clientside. 

    Are there any additional steps i need to take to validate clientside using my own custom validator ?

    Friday, December 2, 2011 5:46 AM

Answers

  • User-474980206 posted

    Ok, Ive followed this example and built a custom validator and registered it in application startup.  The example then goes on to create the javascript validation logic.  Correct me if im wrong, but isnt the whole point of mvc validation so that we create the validation rules once and then that rule will work for both client and server side ?

    just like webform validation, if you create a custom validator, you need to create both a client side routine, and a serverside routine. It looks like you are using the MVC's webforms validation compatiabilty library for you use webform validators. I never used this, but you shoudl just create a webform validator like you did in webforms, and place it on the page. if you did not write a custom validaiton server control, you need to render the validation hookup routines to register the validator. (remember the validations are span with ids, that are added to validation collection via javascript). 

    I don't believe this is a very good direction to take with MVC. You should switch from server controls to html helpers and use the jquery/unobtrusive validation library. see jquery validation docs for writing methods.

    I think MVC jquery client validators are a little easier to write then webform ones were, but there is a little more plumbing if you want unobtrusive support.

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 2, 2011 12:56 PM
  • User-474980206 posted

    mvc2 used the webform engine, and thus uses web form client validators. look at the webforms documentation for using a validator. You should be using the CustomValidator, where you supply the name of the client validation routine.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 6, 2011 11:17 AM

All replies

  • User1444272184 posted

    Refer the below link

    http://www.codeproject.com/KB/aspnet/CustomClientSideValidatio.aspx

    http://forums.asp.net/t/1731351.aspx/1

    Friday, December 2, 2011 5:58 AM
  • User65893105 posted

    Unfortunately my project is using mvc2.   all the examples i can find make use of DataAnnotationsModelValidator which is only available in .net4.

    How can i use clienside validation with mvc 2 ?

    Friday, December 2, 2011 6:04 AM
  • User65893105 posted

    I should also add that im working on an existing project.  the custom validators are specified in the data layer, using the .net 3.5 framework.  i cant change this as its a production system and at the moment our servers are setup to use .net 3.5 only.

    So im using mvc2 and .net 3.5.  Im having a real headache just trying to get something as simple as clienside validation working !

    Friday, December 2, 2011 6:13 AM
  • User1444272184 posted

    Reply this link contains client side custom validations in mvc2

    http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx

    Friday, December 2, 2011 6:16 AM
  • User65893105 posted

    Ok, Ive followed this example and built a custom validator and registered it in application startup.  The example then goes on to create the javascript validation logic.  Correct me if im wrong, but isnt the whole point of mvc validation so that we create the validation rules once and then that rule will work for both client and server side ?

    I might just as well just create the javascript validation myself without creating a custom validator, it seems a bit poinless to me and just creates more work.  Have I got this wrong ??  Why would i bneed to create a clienside validator as well ?  heres what the example says

    'At this point, we still need to write the actual JavaScript validation logic as well as the hookup to the JSON metadata. For the purposes of this demo, I’ll put the script inline with the view.'

    <script type="text/javascript">
      Sys.Mvc.ValidatorRegistry.validators["price"] = function(rule) {
        // initialization code can go here.
        var minValue = rule.ValidationParameters["min"];
    
        // we return the function that actually does the validation 
        return function(value, context) {
          if (value > minValue) {
            var cents = value - Math.floor(value);
            if (cents >= 0.99 && cents < 0.995) {
              return true; /* success */
            }
          }
    
          return rule.ErrorMessage;
        };
      };
    </script>
    Friday, December 2, 2011 6:58 AM
  • User65893105 posted

    can anyone give me a simple step by step guide to implementing clienside validation with custom validators ?  I cant belive this is taking so long !

    with webforms id have had this up and running in a few minutes, so far ive spent a day on it and its still not working.

    anyone ?

    Friday, December 2, 2011 8:37 AM
  • User1224940435 posted

    Hi,

    Please provide following information

    Are you using unobstrusive validation ? If yes than there is diffrent way to register client side validation.

    Friday, December 2, 2011 12:39 PM
  • User-474980206 posted

    Ok, Ive followed this example and built a custom validator and registered it in application startup.  The example then goes on to create the javascript validation logic.  Correct me if im wrong, but isnt the whole point of mvc validation so that we create the validation rules once and then that rule will work for both client and server side ?

    just like webform validation, if you create a custom validator, you need to create both a client side routine, and a serverside routine. It looks like you are using the MVC's webforms validation compatiabilty library for you use webform validators. I never used this, but you shoudl just create a webform validator like you did in webforms, and place it on the page. if you did not write a custom validaiton server control, you need to render the validation hookup routines to register the validator. (remember the validations are span with ids, that are added to validation collection via javascript). 

    I don't believe this is a very good direction to take with MVC. You should switch from server controls to html helpers and use the jquery/unobtrusive validation library. see jquery validation docs for writing methods.

    I think MVC jquery client validators are a little easier to write then webform ones were, but there is a little more plumbing if you want unobtrusive support.

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, December 2, 2011 12:56 PM
  • User65893105 posted

    its mvc2 so i belive unobtrussive validation isnt available ?  (im new to mvc, this is my first app)

    Monday, December 5, 2011 4:56 AM
  • User65893105 posted

    I am using html helpers

    <%=Html.TextBoxFor(x=>x.CancelDate) %>

    and my custom validator in the model

    [DateIsGreaterThanAttribute("Policy.StartDate", ErrorMessage = "The cancellation date can't be less than the policy start date")]

    public sealed class DateIsGreaterThanAttribute : ModelAwareValidationAttribute
        {
            //this is needed to register this attribute with foolproof's validator adapter
            static DateIsGreaterThanAttribute() { Register.Attribute(typeof(DateIsGreaterThanAttribute)); }
            private DateTime _date;
    
            public DateIsGreaterThanAttribute(string date)
                : base()
            {
                _date = CustomValidators.ParseTimeInterval(date);
    
            }
    
            public override bool IsValid(object value, object container)
            {
                if (value == null)
                {
                    return true;
                }
                DateTime dateValue = (DateTime)value;
                return (dateValue > _date);
            }
        }
    
    
    is this the best way ? or is there a better alternative ?
    Monday, December 5, 2011 5:04 AM
  • User65893105 posted

    ignore the DateIsgreaterThan attribute i posted previously, I was using FoolProof MVC which Ive decided to abanadon, this is the method im currently using

    in my model I have this attribute

    [DateGreaterThanAttribute("Policy.StartDate", ErrorMessage = "The cancellation date can't be less than the policy start date")]

    and this is the definition.  Serverside is fine but i cant get clientside to work

    public sealed class DateGreaterThanAttribute : ValidationAttribute
        {
            private DateTime _date;
    
            public DateGreaterThanAttribute(string date)
                : base()
            {
                _date = CustomValidators.ParseTimeInterval(date);
             
            }
    
            public override bool IsValid(object value)
            {
                if (value == null)
                {
                    return true;
                }
                DateTime dateValue = (DateTime)value;
                return (dateValue > _date);
            }
        }
    Monday, December 5, 2011 5:09 AM
  • User-1280676833 posted

    Hi,

    You just need add this line in your view:

    <% Html.EnableClientValidation(); %>

    For details, please check Scott Gu's blog, and see the Enabling Client-Side Validation section.

    Hope this helpful

    Regards

    Young Yang

    Tuesday, December 6, 2011 4:15 AM
  • User65893105 posted

    yes, thats already added in my master page

    managed to get the whole thing working now though

    Tuesday, December 6, 2011 10:16 AM
  • User-474980206 posted

    mvc2 used the webform engine, and thus uses web form client validators. look at the webforms documentation for using a validator. You should be using the CustomValidator, where you supply the name of the client validation routine.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 6, 2011 11:17 AM