How to change 'data-val-number' message validation in MVC while it is generated by @Html helper

后端 未结 14 1693
面向向阳花
面向向阳花 2020-11-28 03:44

Assume this model:

Public Class Detail
    ...
    
    
         


        
14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 04:24

    Here is another solution in pure js that works if you want to specify messages globally not custom messages for each item.

    The key is that validation messages are set using jquery.validation.unobtrusive.js using the data-val-xxx attribute on each element, so all you have to do is to replace those messages before the library uses them, it is a bit dirty but I just wanted to get the work done and fast, so here it goes for number type validation:

        $('[data-val-number]').each(function () {
        var el = $(this);
        var orig = el.data('val-number');
    
        var fieldName = orig.replace('The field ', '');
        fieldName = fieldName.replace(' must be a number.', '');
    
        el.attr('data-val-number', fieldName + ' باید عددی باشد')
    });
    

    the good thing is that it does not require compiling and you can extend it easily later, not robust though, but fast.

提交回复
热议问题