Home > Blockchain >  ASP.NET Core Double validation dots doesnt work
ASP.NET Core Double validation dots doesnt work

Time:07-22

In my validation, my input is double, but when I type for example "3.14", I got error message: "The value '3.14' is not valid for Fueling", if I do it with commas (,) its working. I want to use both dots and commas for input. What should I do? My globalization is HU-hu (hungary, basic separator is commas).

EDIT - Code

[Display(Name = "Tankolás")]
    [DisplayFormat(DataFormatString = "{0} l", ApplyFormatInEditMode = false)]
    [FuelValidation]
    public double? Fueling { get; set; }

HTML

<div >
                <label asp-for="Fueling" ></label>
                <input asp-for="Fueling"  placeholder="Tankolás" />
                <span asp-validation-for="Fueling" ></span>
            </div>

Validation:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var record = (RoadRecord)validationContext.ObjectInstance;
        if (value != null)
        {
           value = double.Parse(value.ToString(), new CultureInfo("hu-HU"));
            if (!((double)value <= 0))
            {
                
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult("Legyen nagyobb mint 0");
            }
            
        }
        else
        {
            return ValidationResult.Success;
        }
    }

CodePudding user response:

Maybe you can consider using a piece of JavaScript code to assist with validation. If you just use custom Validation, you will get null when you pass 3.14, so you can't proceed with validation.

Use JS in the view to judge the passed parameters, if it is 3.14, change it to 3,14 for passing will solve this problem.

Below is my test code,you can refer to it:

<form asp-action="Index">
    <div >
                    <label asp-for="Fueling" ></label>
                    <input id="Fueling" asp-for="Fueling"  placeholder="Tankolás" />
                    <span asp-validation-for="Fueling" ></span>
    </div>
    <div >
        <button onclick="Test()" >Submit</button>
    </div>

</form>
<script>
    function Test()
    {
        var param = $("#Fueling").val();
        if (param.indexOf(".") != -1) 
        {
            param = param.replace(".",",");
        }
        $("#Fueling").val(param);
    }
</script>

Test Result:

When I enter 3,14:

enter image description here enter image description here

When I enter 3.14:

enter image description here

After processing:

enter image description here enter image description here

  • Related