Time Picker Validation

11 posts, 0 answers
  1. Julian Welby-Everard
    Julian Welby-Everard avatar
    4 posts
    Member since:
    Oct 2008

    Posted 19 Jun 2009 Link to this post

    I have several questsions about Validation of the the RadTimePicker control as follows.

    My current code does the following
        <telerik:RadTimePicker ID="RadTimePicker1"   
            runat="server"   
            EnableEmbeddedSkins="False"   
            ImagesPath="~/Images/Calendar"   
            Skin="Safe"   
            Width="90px">  
            <TimePopupButton CssClass="" HoverImageUrl="~/Images/Calendar/clockHover.gif" ImageUrl="~/Images/Calendar/clock.gif" /> 
            <TimeView Culture="English (United Kingdom)" EnableEmbeddedSkins="False" Skin="Safe" runat="server" > 
            </TimeView> 
            <DateInput EnableEmbeddedSkins="False" LabelCssClass="" Width="" Skin="Safe" runat="server">  
            </DateInput> 
            <Calendar EnableEmbeddedSkins="False" ImagesPath="~/Images/Calendar" UseColumnHeadersAsSelectors="False" UseRowHeadersAsSelectors="False" ViewSelectorText="x" Skin="Safe" runat="server">  
            </Calendar> 
            <DatePopupButton CssClass="" HoverImageUrl="~/Images/Calendar\datePickerPopupHover.gif" ImageUrl="~/Images/Calendar\datePickerPopup.gif" Visible="False" /> 
        </telerik:RadTimePicker> 
        <asp:customvalidator clientvalidationfunction="validtime" cssclass="hourvalidator" setfocusonerror="true" id="starttimevalidator2" controltovalidate="RadTimePicker1" enableclientscript="true" runat="server" Display="Dynamic" >*</asp:customvalidator> 
       
    I also have onblur code declared in the code behind this deals with values the user enters, the customvalidator is a client side validator, this validates the time enetered is between a start and end value, is rounded to the correct number of minites ie 00, 15, 30, and 45, is a valid time. Also a blank is a Valid entry

    but I have noticed the following issues
    1) When the user eners a time the zzzzz, I dont get the custom validtor to fire. I have tried with OnError this works, but the .net validator does not fire, and therefor the page does not see the error!, also If I set a flag to say its invalid how do I make sure that is unset?

    2) I would like to overide the code that parses the time so that I can control when '!' is shown on the entry field, If I can access this then some of the issues in 1 would dealt with. All I would need to do is control when the control is valid/invalid

    3) I need to ask the control in codebehind if it is valid, this includes entry of zzzzz etc.

    4) Because I have a custom CSS skin I don't get the invalid time eneted '!', what do i need in the skin.css for correct this (minor issue)

    (properly more to come as I keep digging)


    Julian


  2. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 19 Jun 2009 Link to this post

    Hi Julian,

    Try setting the ValidateEmptyText property of the CustomValidator to true and see whether the Validator function is getting fired on entering string value.


    ASPX:
     
       <asp:CustomValidator ID="CustomValidator1" ControlToValidate="RadTimePicker1"  ClientValidationFunction="ValidateFun" ValidateEmptyText="true" runat="server" ErrorMessage="Enter a Valid Time"></asp:CustomValidator> 

    Shinu
  3. Julian Welby-Everard
    Julian Welby-Everard avatar
    4 posts
    Member since:
    Oct 2008

    Posted 19 Jun 2009 Link to this post

    Thanks

    just tried that and still no luck,

    Looking into the code the Rad control is parsing and rendering the "!" icon, once this is done the client side validation does not fire, (i think its down to the point, why bother if its invalid), I need it to fire so I can set the page to isValid = False so I can get the same style of messaging out.

    Julian
  4. Tsvetoslav
    Admin
    Tsvetoslav avatar
    1823 posts

    Posted 24 Jun 2009 Link to this post

    Hi Julian Welby-Everard,

    Straight to your questions:

    1. Concerning the first issue, the custom validator not being fired is expected, since validators are triggered on the onchange dom event whereas when the time picker contains an invalid value there is no actual value change and the onchange event is not fired on purpose. In order to handle your custom error logic just attach a client event handler to the OnError client event of the DateInput subobject of the TimePicker as you have correctly notices.

    2. It is not possible to override the parsing function of the time picker without breaking the code of the control since this function is intended for internal use only and is not to be exposed as a public one.

    3. The time picker control does not have a IsValid or similar server-side property, however, you can obtain its value and check it with a regular expression patter to ascertain if it is a valid time.

    4. The css class that sets the controls invalid style is named: riTextBox riError.

    I hope this information helps.

    Best wishes,
    Tsvetoslav
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  5. Julian Welby-Everard
    Julian Welby-Everard avatar
    4 posts
    Member since:
    Oct 2008

    Posted 26 Jun 2009 Link to this post

    Hi

    Thanks for the heads up,

    From a support call I have been informed that using client side OnError I can keep track of each control that is in error, then using customValidators check the array created,This sort of works.

    Using client side events OnValueChanged and OnMouseOut I can check the value entered while this works It does not do what I need. I need to show the control is in error ie show the error trangale. When I call sender.raise_error(args); the triangle flashes.

    I can not be the only persion who wants to validate a time entered matches business rules.
    Our rules are a valid time is one between 00:00 and 23:45, only allowing minutes to be 00, 15, 30 and 45 and Blanks are alowed as times are not requied

    There seems no way of doing this type of vlidation, if a user enteres 12:12 for the time then I want to show it as in error, not reset it. If the user clicks the save button I dont want to save that time, or a blank time, I want the page to fail validation.

    Julian


  6. Pavlina
    Admin
    Pavlina avatar
    6187 posts

    Posted 01 Jul 2009 Link to this post

    Hello Julian,

    In order to set a valid time to be between 00:00 and 23:45, only allowing minutes to be 00, 15, 30 and 45, you should set TimeView-Interval property.
    ASPX:
     <telerik:RadTimePicker ID="RadTimePicker" runat ="server"      
    TimeView-Interval="00:15:00">     
    ........... 

    About the validation when type invalid time, I suggest you handle OnDateSelected event and check if the entered date/time is valid.

    Regards,
    Pavlina
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  7. Sune Dyrberg
    Sune Dyrberg avatar
    12 posts
    Member since:
    Nov 2008

    Posted 30 Jun 2010 Link to this post

    Hi Julian (or Telerik Team)

    I have the same validation problem with the time picker. Did you ever found a solution to this problem? 

    /Per
  8. Pavlina
    Admin
    Pavlina avatar
    6187 posts

    Posted 02 Jul 2010 Link to this post

    Hi Sune,

    Could you please elaborate a bit more on your scenario? What is the exact problem with time picker validation?

    All the best,
    Pavlina
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  9. Chris Hoare
    Chris Hoare avatar
    4 posts
    Member since:
    Aug 2008

    Posted 02 Jul 2010 Link to this post

    Ok, I i rember correctly this is how I did it (in our app)
    First I created a hidden field on the page, and a custom validator, plus teleik time picker
    <asp:HiddenField ID="errorstate" runat="server" Value="" /> 
    <telerik:RadTimePicker ID="RadTimePicker1" runat="server" Width="90px" EnableEmbeddedSkins="False" Skin="Safe" > 
        <TimePopupButton CssClass="" HoverImageUrl="~/Images/Calendar/clockHover.gif" ImageUrl="~/Images/Calendar/clock.gif" /> 
        <TimeView Culture="English (United Kingdom)" EnableEmbeddedSkins="False" Skin="Safe" runat="server" ></TimeView>  
        <DateInput LabelCssClass="" Width="" runat="server" > 
            <ClientEvents OnBlur="CheckRadDatePickerTime"  OnValueChanged="CheckRadDatePickerTime" OnMouseOut="CheckRadDatePickerTime" OnError="OnRadDatePickerError" />   
        </DateInput> 
        <Calendar ImagesPath="~/Images/Calendar" UseColumnHeadersAsSelectors="False" UseRowHeadersAsSelectors="False" ViewSelectorText="x" runat="server"></Calendar> 
        <DatePopupButton CssClass="" HoverImageUrl="~/Images/Calendar/datePickerPopupHover.gif" ImageUrl="~/Images/Calendar/datePickerPopup.gif" Visible="False" /> 
    </telerik:RadTimePicker> 
    <asp:customvalidator clientvalidationfunction="validtime" cssclass="hourvalidator" setfocusonerror="true" id="timevalidator1" controltovalidate="TextBox1" enableclientscript="true" runat="server" >*</asp:customvalidator> 
    Java script functions created for validation, CheckRadDatePickerTime and validtime
    function validateTime(control)  
    {  
        //debugger;  
        var controlID  
        controlChanged = new String(control.id);  
        if (controlChanged == 'undefined')  
        {  
            controlChanged = new String(control._clientID);  
        }  
        controlID = controlChanged.replace(/(.*)_(ctl\d{2,})(_Line_)(Start|Lunch|Finish|LineTotal)(_TextBox1|_RadTimePicker1)(_dateInput)?(_text)?/ig, function re_match($0, $1, $2, $3, $4, $5) {return $1 + '_' + $2 + $3 + $4 + $5;});  
        for(ix=0; ix<Page_Validators.length; ix++)  
        {  
            if(Page_Validators[ix].controltovalidate == controlID)  
            {  
                var value = control.value;  
                var val = Page_Validators[ix];  
                if (typeof val.clientvalidationfunction == "string")  
                {  
                    var args = {Value:value, IsValid:true};  
                    if (eval(val.clientvalidationfunction + "(val,args);"))  
                    {  
                        val.style.visibility = "hidden";  
                    }  
                    else  
                    {  
                        val.style.visibility = "visible";  
                    }  
                }  
                return;  
            }  
        }  
    }  
     
    function validtime(oSrc, args)  
    {  
        //debugger;  
        args.IsValid = validTimeEntered(args.Value);  
        return args.IsValid;  
    }  
     
    // AND some nasty JS in the codebehing of the page  
     
            Dim sb As StringBuilder = New StringBuilder()  
            sb.AppendLine("<script language=""javascript"" type=""text/javascript"">")  
     
            sb.AppendLine("function validTimeEntered(value)")  
            sb.AppendLine("{")  
            'sb.AppendLine("debugger;")  
            sb.AppendLine("try")  
            sb.AppendLine("{")  
            sb.AppendLine("if(value==""hh:mm"")")  
            sb.AppendLine("return true;")  
            sb.AppendLine("if(value=="""")")  
            sb.AppendLine("return true;")  
            sb.AppendLine("if(value.length > 5)")  
            sb.AppendLine("valuevalue = value.replace(/(\d{4})(-)?(\d{2})(-)?(\d{2})(-)?(\d{2})(-)?(\d{2})(-)?(\d{2})/gi, function re_match($0, $1, $2, $3, $4, $5, $6, $7, $8, $9) {return $7 + ':' + $9 ;});")  
            sb.AppendLine("var str = new String(value);")  
            sb.AppendLine("strstr = str.replace(/^(\d{1,2}):(\d{0,2})$/ig, function re($0,$1,$2){return $1 + "":"" + ($2==""""?""00"":$2);})")  
            sb.AppendLine("str = new String(value);")  
            sb.AppendFormat("return str.match(/{0}/) != null;", validateHoursRegEx(CType(Me.Page.Master, Cwp.Pages.cwpMasterPageBase).RootConfig().RootConfig.TimeshheetEntryHours)).AppendLine()  
            sb.AppendLine("}")  
            sb.AppendLine("catch(e)")  
            sb.AppendLine("{")  
            sb.AppendLine("return false;")  
            sb.AppendLine("}")  
            sb.AppendLine("}")  
     
            sb.AppendLine("</script>")  
     
            Dim csm As ClientScriptManager = Page.ClientScript  
            csm.RegisterClientScriptBlock(Me.GetType(), "TimeValidation", sb.ToString())  
     
            'If ConfigReader.GetRootConfig.RootConfig.TimeFieldConfiguration.Mode <> TimeFieldModes.TextBox Then  
                sb = New StringBuilder  
                Dim validValues As StringString = String.Empty  
                If ConfigReader.GetRootConfig.RootConfig.TimeshheetEntryHours = TimesheetHourEntry.Any Then  
     
                ElseIf ConfigReader.GetRootConfig.RootConfig.TimeshheetEntryHours = TimesheetHourEntry.Quarter Then  
                    validValues = "00,15,30,45" 
                ElseIf ConfigReader.GetRootConfig.RootConfig.TimeshheetEntryHours = TimesheetHourEntry.Half Then  
                    validValues = "00,30" 
                ElseIf ConfigReader.GetRootConfig.RootConfig.TimeshheetEntryHours = TimesheetHourEntry.Hour Then  
                    validValues = "00" 
                End If  
     
                sb.Append("function CheckRadDatePickerTime(sender, args)")  
                sb.Append("{")  
                If validValues <> String.Empty Then  
                sb.Append("var timeEntered = args._newValue;")  
                sb.Append("if (timeEntered != '' && timeEntered != undefined) ")  
                    sb.Append("{")  
                sb.Append(" if (!validateTimeEntred(timeEntered)) {")  
                    sb.Append("OnRadDatePickerError(sender, args);")  
                    sb.Append("sender._invalid=true;")  
                    sb.Append("}else{")  
                    sb.Append("sender._invalid=false;")  
                    sb.Append("}")  
                    sb.Append("}")  
                End If  
                sb.Append("}")  
            sb.Append("function validateTimeEntred(timeEntered) {")  
            sb.Append("var ary = timeEntered.split(':');")  
            sb.Append(String.Format("var validvalues = '{0}';", validValues))  
            sb.Append("return !((validvalues.indexOf(ary[1]) < 0 || parseInt(ary[0]) < 0 || parseInt(ary[0]) > 23 || !validTimeEntered(timeEntered)));")  
            sb.Append("}")  
                If sb.Length > 0 Then  
                    Dim cstype As Type = Me.GetType()  
                    ' Get a ClientScriptManager reference from the Page class.  
                    Dim cs As ClientScriptManager = Page.ClientScript  
     
                    ' Check to see if the client script is already registered.  
                    If (Not cs.IsClientScriptBlockRegistered(cstype, "CheckRadDatePickerTime")) Then  
                        cs.RegisterClientScriptBlock(cstype, "CheckRadDatePickerTime", sb.ToString(), True)  
                    End If  
                End If  
            'End If  
     
     
     
     
    and finaly on the code behind wired up some more js as follows
                    RadTimePicker1.DateInput.Attributes.Add("onfocus", "javascript:timeentry_OnEnter(this);return true;")  
                    RadTimePicker1.DateInput.Attributes.Add("onblur", "javascript:timeentry_OnBlur(this);validateTime(this);") 

    The way it works is that if a time is eneted a JS function is called, if the time is invalid ie 99:99 or 10:20 and we only allow quarter hours then a flag is set on the page to indicate an error, the custom error handler then checks all timefields on the screen to see if any time fields are still in error (we chan have upto 45) the post is stopped and error is displayed.

    Also if a time field is found to be in error is error icon is dispalyed


    Hope this helps you find the solution you may need

    Julian
  10. Pavlina
    Admin
    Pavlina avatar
    6187 posts

    Posted 08 Jul 2010 Link to this post

    Hi Chris,

    Thank you for sharing your solution with the community. I am sure it would be helpful for anyone searching such functionality.

    Greetings,
    Pavlina
    the Telerik team
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  11. Sune Dyrberg
    Sune Dyrberg avatar
    12 posts
    Member since:
    Nov 2008

    Posted 08 Jul 2010 Link to this post

    Hi Julian

    I would also like to thank you for sharing your solution.It helped me find a solution to my problem.

    Greetings,
    Per
Back to Top