C# ASP.NET - User keystroke validation and input character into correct place

56 views Asked by At

I am looking to have a time field that starts with 00:00 which is the exact format I want.

As the user types the time I want to read the keystroke and place it within my preassigned value.

--Edit-- removed previous validation code which didn't really pertain to finding out how to validate upon keystroke.

2

There are 2 answers

2
Albert D. Kallal On

Perhaps you use the built in textmode = time.

It not 100% as you ask, but your specification has some "issues".

for example, if I want 10:30, or 1:30?

so, a 1, and a 3 for 10:03 don't make sense, since I might want:

 1:03
10:03
 1:30
10:30

So, hitting a 1, and then a 3 CAN'T really result in 10:03, since then how would you enter 10:30?

As I stated, you probably best to use the default text mode = time.

It will do MOST of what you ask, does not allow user to enter NON number chars, and formats for most of what you want.

So, say I want 10:30

If I enter 1,0,3, then that's what I get e.g., this:

Markup:

       <h3>enter time</h3>
        <asp:TextBox ID="txtTime" runat="server"
            TextMode="Time">
        </asp:TextBox>

So, for 10:30, then 1,0,3

enter image description here

Now, of course above has AM/PM

We just have to try and google, and see if am/pm can be removed.

And if you need more then 12 hours, then again, the above may well not help you.

4
Chris Glenn On

So here is what I found to validate as the user types.

It still shows what they typed before it removes it but it was as close as I could get.

Also if anyone knows a way to pass the parameters in from the eventclick without having to declare them in the function so I can reuse this on multiple fields passing in the different variables would be great!

Basically I setup a session for per user bases that will hold the value of the field when a key is pressed down in memory and when released it will pass the new value through a validation check and if it passes then all good otherwise it resets the value with what is in the memory storage.

Under the program.cs I added

--code

//Use for session control
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
});

var app = builder.Build();
// end the Session Control 

// Add the Session Control then go to SessionController
app.UseSession();

Under the Session Controller

--code

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Products.Models;

namespace Products.Controllers
{
    public class SessionController : Controller
    {
        private readonly IHttpContextAccessor _contextAccessor;
        public SessionController(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
        public FieldModel EventHandler(FieldModel model)
        {
            string sessionName = model.sessionName;
            
            if (model.keystroke == "down")
            {
                //This is passing in the current value of the field.  Just need to save it in the Session
                string fieldString = JsonConvert.SerializeObject(model);
                _contextAccessor.HttpContext.Session.SetString(sessionName, fieldString);
            }
            else if (model.keystroke == "up")
            {
                //TODO - This is passing in the new character. Get the session
                FieldModel priorModel = new FieldModel();
                string fieldString = _contextAccessor.HttpContext.Session.GetString(sessionName);
                priorModel = JsonConvert.DeserializeObject<FieldModel>(fieldString);

                bool validate = false;
                //TODO - This is passing in the new character.  Validate the value for the field
                if (model.fieldType == "time")
                {
                    if (model.fieldNewValue.Length < 5)
                        validate = true;
                }
                //TODO - If validation passes allow the update
                if (validate == true)
                {
                    //fieldString = JsonConvert.SerializeObject(model);
                    //_contextAccessor.HttpContext.Session.SetString(sessionName, fieldString);
                    
                }
                //TODO - If validation fails reset the field to the current value
                else
                {
                    //fieldString = JsonConvert.SerializeObject(priorModel);
                    //_contextAccessor.HttpContext.Session.SetString(sessionName, fieldString);
                    model = priorModel;
                }
            }
            return model;
        }
    }
}

For the webpage view I used the following code --code

<script>

    function FieldValidatorD() {
        let sessionName_ = `time`;
        let fieldID_ = `time`;
        let fieldType_ = `time`
        let keystroke_ = `down`
        let input = document.querySelector(`#` + fieldID_).value;        
        let json = {
          sessionName: sessionName_,
          fieldID: fieldID_,
          fieldType: fieldType_,
          fieldCurrentValue: input,
          fieldNewValue: input,
          keystroke: keystroke_
        };        
     //console.log(json);
        $.ajax({
            type: `json`,
            data: json,
            url: `/Session/EventHandler`,
            async: false,
            success: function (data) {
                //console.log(data);
                //console.log(data.fieldNewValue);
            }
        })
    };
    function FieldValidatorU() {
        let sessionName_ = `time`;
        let fieldID_ = `time`;
        let fieldType_ = `time`
        let keystroke_ = `up`
        let input = document.querySelector(`#`+fieldID_).value;
        let json = {
            sessionName: sessionName_,
            fieldID: fieldID_,
            fieldType: fieldType_,
            fieldCurrentValue: input,
            fieldNewValue: input,
            keystroke: keystroke_
        };
        //console.log(json);
        $.ajax({
            type: `json`,
            data: json,
            url: `/Session/EventHandler`,
            async: false,
            success: function (data) {
               //console.log(data);
               //console.log(data.fieldNewValue);
                //fill in the textbox by injecting the html into the field
                $(`#` + fieldID_).val(data.fieldNewValue);
            }
        })
    };
 

</script>