简体   繁体   中英

I have to validate a text box in .NET MVC where the text box value is less than or equal the difference of two column values?

A Text box field has to be validated such that the value must be less than or equal to the calculated value (Difference between two column values). For example, I have two Columns TodaysDateTime and TomorrowsDateTime the difference between these two is calculated in mins this mins value is the maximum value for the text box.

Thanks in Advance!

if(Convert.ToInt32(textbox1.Text) <= (TomorrowsDateTime - TodaysDateTime))
{
    // show alert or error dialogue
}

Yes. You can validate at model level by using Custom Validation

(Assuming you are ready to prepare your model accordingly ie ViewModel ).

Your Model:

 [testValidator]
    public partial class Cal
    {
        public DateTime todayDateTime { get; set; }
        public DateTime tommorwDateTime { get; set; }
        public int result {get; set;}
    }

CustomValidator:

   class testValidator : AbstractValidator<test>
   {
    public override ValidationResult Validate(test obj)
    {

    if(Convert.ToInt32(obj.result ) <= (todayDateTime  - tommorwDateTime ))
        {
            return ValidationResult.Success;  
        }
    else
        {
            return new ValidationResult("Please Enter a Valid Dates.");  
        }

    }

}

At Your controller. you can simply check Model.IsValid

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM