开发者

ASP .NET ajax field validation

What would be the easiest way to have the color of a text field in an ASP .NET MVC form changed according to a value just entered BEFORE form submission.

The color to be used is returned by a DB query.

For example:

The query returns Red if the number enter in the field is lower then the Quantity registered for the item in the 开发者_JAVA百科DB.

Thanks


You can do it like in the example below, using jQuery :

//bind a function to the blur even of the text field
$("#the-imput-control").blur(function () {
     var value = this.val();
     //send the value to the server and then process the result.
     $.getJSON("yourUrl", { key: value }, function(data) {
         //return a json object with a property "color"
         //and use its value to set the text field's color
         $("#the-imput-control").css("color", data.color);
     });
     //you can of course use another ajax function depending on your needs.
});


You would like to have an event onclick for the submit button or on changing the quantity to retrieve the quantity of the product.

You can also load a color in the beginning but the stock may change during the user's input.

For example

  1. User loads an order form, quantity in stock: 4, maybe you set the color to orange because it's low...
  2. user fills out the form, some other users order 3 in total, 1 is left in stock
  3. user would like to order 2 items.
  4. user clicks on submit, you have your event checking the quantity and display a message/change the color of textbox

As I understood you would not have a postback if the amount in db is lower than the amount ordered.... but consider that users may not have javascript turned on, you should also implement in server side.

Personally I would just do it on server side, because on client side is just an extra functionality which you cannot rely on.


If it doesn't impose any security risk, it would be best to cache the available quantity for the products, instead to go to the server for validation. This way, the UI will be more responsive - and the user experience will be better. So, basically,

// JS
var availableQuantities = [10, 15, 30];
$(".the-imput-control").blur(function () {
     var value = $(this).val();

     var productIndex = $(this).parent().children().index(this); // sort of

     $(this).toggleClass('invalid', (availableQuantities[productIndex] < value));
});

// CSS
.invalid { color: red; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜