简体   繁体   中英

Validation for Minimum and Maximum Price

I have 2 textbox one is of Minimum Price and other is of Maximum Price.I want the validation when one enter the Minimumm price greater than Maximum Price that "you have enter the Minimum Price greater than Maximum Price". I have tried Custom Validation for this and even written ajax for this as well My code goes as follows:

<input type="text" id="MinimumPrice"/>
<input type="text" id="MaximumPrice"/>

$('#MaximumPrice').blur(function () {
            var url1 = "/Profile/CheckMaxPrice";
            var max = $('#MaximumPrice').val();
            var min= $("#MinimumPrice").val();
            $.get(url1, { maximum: max, minimum: min }, function (data) {
                if (data.maximum<data.minimum) {
                    alert("ok");
                }
            });
        });

and the function as

[AllowAnonymous]
        [HttpPost]
        public ActionResult CheckMaxPrice(int maximum, int minimum)
        {
            if (maximum < minimum)
            {

                return Json("maximum", JsonRequestBehavior.AllowGet);

            }
            else 
            {
                return Json("minimum", JsonRequestBehavior.AllowGet);
            }
        }

and even written the script as well as follows:

$("#MaximumPrice").blur(function () {
           var min = $("#MinimumPrice").val();
            var max = $("#MaximumPrice").val();
            if (min > max)
            {
                //$("#MaximumPrice").append("<p>Min Price can not be greater tham Max Price</p>");
                alert("Min Price can not be greater than Max Price");
            }
        });

but not getting the proper result.

To compare numbers, you're going to need to turn the values into numbers, otherwise 17 will be less than 2.

var min = parseInt($("#MinimumPrice").val(),10);
var max = parseInt($("#MaximumPrice").val(),10);
if (min > max){
    alert("Min Price can not be greater than Max Price");
}

I'm assuming you're using whole numbers, otherwise you can use parseFloat()

$("#MinimumPrice, #MaximumPrice").change(function (e) {
    var lil = parseInt($("#MinimumPrice").val(), 10);
    var big = parseInt($("#MaximumPrice").val(), 10);
    $('#lil').text(lil);
    $('#big').text(big);
    if (lil > big) {
        var targ = $(e.target);
        if (targ.is("#MaximumPrice")) {
            alert("Max must be greater than Min");
            $('#MaximumPrice').val(lil);
        }
        if (targ.is("#MinimumPrice")) {
            alert("Min must be less than Max");
            $('#MinimumPrice').val(big);
        }
    }
});

jsFiddle

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