Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

asp.net mvc 2 - Jquery validation - allow number without the leading zero?

I'm using jquery validation (http://docs.jquery.com/Plugins/Validation) like so:

    var $__field = $("#selector");  
    if ($__field.is(":visible")) {  
        $__field.rules('add', { required: true });
        $__field.rules('add', { number: true });
    } 

If the user enters a number without a leading zero, eg .5 then jquery validation says "Please enter a valid number."

How can I change the validation to allow number entry without requiring the leading zero?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is with the regular expression used for numbers. Looking at the latest version, lines 1021-1023, we've got:

number: function(value, element) {
    return this.optional(element) || /^-?(?:d+|d{1,3}(?:,d{3})+)(?:.d+)?$/.test(value);
},

The problem is that this first chunk, which looks for leading negative sign and numbers, either individual or in groups of three separated by commas, is not optional:

(?:d+|d{1,3}(?:,d{3})+)

Tacking a ? on the end will make it optional:

(?:d+|d{1,3}(?:,d{3})+)?

With this update, you can either modify your local copy of the plugin, changing the regular expression to the modified version, or add a replacement validation method to your javascript:

jQuery.validator.addMethod("number", function(value, element) {
    return this.optional(element) || /^-?(?:d+|d{1,3}(?:,d{3})+)?(?:.d+)?$/.test(value);
}, "Please enter a valid number.");

On any page with this addMethod call, the number validation method will be overridden to do a number validation that doesn't require a leading zero.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...