C# ASP.NET - 用户击键验证并将字符输入到正确的位置

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

提问人:Chris Glenn 提问时间:9/1/2023 最后编辑:Chris Glenn 更新时间:9/7/2023 访问量:50

问:

我希望有一个以 00:00 开头的时间字段,这是我想要的确切格式。

当用户键入时间时,我想读取击键并将其放在我预先分配的值内。

--编辑-- 删除了以前的验证代码,这些代码与了解如何在击键时进行验证无关。

C# asp.net 验证 Blazor 击键

评论

0赞 MrC aka Shaun Curtis 9/1/2023
相当全面的规格,你准备为这个时间字段支付多少钱?撇开玩笑不谈,你在哪里使用它,除了一些基本的代码之外,你还做了什么?我建议考虑某种形式的正则表达式检查器,而不是所有那些复杂的逻辑。
0赞 Chris Glenn 9/5/2023
这段代码并不是那么重要,我真的在寻找如何每次击键而不是在提交按钮上运行脚本。
0赞 Panagiotis Kanavos 9/7/2023
代码非常重要,因为问题不清楚。您可以用于初学者。您可以使用客户端代码验证击键。事实上,如果标记有效,则可以轻松使用 C# 来验证内容。还有一些花哨的时间选择器组件input type='time'blazor

答:

1赞 Albert D. Kallal 9/4/2023 #1

也许您使用内置的 textmode = time。

它不是 100% 像你问的那样,但你的规范有一些“问题”。

例如,如果我想要 10:30 或 1:30?

所以,1 和 3 表示 10:03 没有意义,因为我可能想要:

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

所以,在10:03打1,然后打3不能,从那以后你怎么进入10:30?

正如我所说,您可能最好使用默认文本模式 = 时间。

它将完成您要求的大部分工作,不允许用户输入非数字字符,以及您想要的大部分内容的格式。

所以,说我想要 10:30

如果我输入 1,0,3,那么这就是我得到的 例如,这个:

标记:

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

所以,对于 10:30,然后是 1,0,3

enter image description here

现在,上面当然有 AM/PM

我们只需要尝试谷歌,看看是否可以删除 am/pm。

如果您需要超过 12 小时,那么上述内容很可能对您没有帮助。

评论

0赞 Chris Glenn 9/5/2023
感谢您的这个片段,它可能应该可以完成这项工作。我真的在寻找某种方式让服务器每次击键进行验证。它是否是一个时间场并不重要,它只是恰好是我目前正在做的事情。我是 ASP.net 的新手,但在FileMaker中,我基本上能够接受用户键入的内容,如果它经过验证,那么它就可以了,否则它只是回发了相同的字符串。在用户端,它看起来只是阻止键入字符,因为他们看不到它的工作。我希望在这个平台上拥有相同的功能。
0赞 Panagiotis Kanavos 9/8/2023
someway to have the server validate per keystroke. 为什么?这除了增加流量和服务器的工作负载,延迟 UI 之外,什么也没提供。如果使用 Blazor Server,则所有内容都已在服务器上运行。发布您的代码
-1赞 Chris Glenn 9/7/2023 #2

因此,这是我发现在用户键入时进行验证的内容。

它仍然显示他们在删除它之前输入的内容,但它尽可能接近我。

此外,如果有人知道一种方法可以从 eventclick 传入参数而无需在函数中声明它们,那么我可以在多个字段上重用它,传入不同的变量会很棒!

基本上,我为每个用户群设置了一个会话,当在内存中按下一个键时,该会话将保留该字段的值,当释放时,它将通过验证检查传递新值,如果它通过,那么一切都很好,否则它会重置内存存储中的值。

在程序下,我添加了 .cs

--法典

//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();

在会话控制器下

--法典

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;
        }
    }
}

对于网页视图,我使用了以下代码 --法典

<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>

评论

0赞 Panagiotis Kanavos 9/7/2023
您使用了标记。这不是 Blazor 代码,也不需要任何代码。为什么要调用服务器来验证*客户端*值?为什么不对初学者使用输入 type='time' 来确保用户不会输入错误的数据?如果确实使用 Blazor,则可以在客户端上处理其他验证。与纯 JS 相同。blazor
0赞 Chris Glenn 9/8/2023
问题是如何验证每次击键。我以时间为例,但我正在寻找在字段键入时验证字段并阻止键入字符。我知道这是可能的,但我不知道如何在这个平台上做到这一点,这就是我问这个问题的原因。如果您能为我指出正确的方向,以便以更好的方式验证每次击键的任何字段,请这样做。我已经搜索过了,除了我发布的内容之外,还没有找到自己做到这一点的方法。
0赞 Panagiotis Kanavos 9/8/2023
此代码不能回答该问题。没有理由调用服务器来执行每次击键的验证。不过,你是否使用 Blazor?如果这样做,为什么不处理组件中的击键事件呢?如果使用 Blazor Server,则服务器已处理所有事件
0赞 Panagiotis Kanavos 9/8/2023
您是否在 Blazor 中检查了在按键时验证输入而不是在更改时验证输入