Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Could you point how to configure  jQuery validator to accept decimal point as comma and doesn't accept characters ?

Posted on 2016-09-30
10
Medium Priority
?
106 Views
Last Modified: 2016-10-03
Hi Experts

Could you point how to configure  jQuery validator to accept decimal point as comma and doesn't accept characters ?

This example accepts characters.
$("#myform").validate({
    //for debug only
    debug: true,
    rules: {
        field: {
            required: true,
            pattern: /^(\d+|\d+,\d{1,2})$/
        }
    },
    messages: {
        field: {
            pattern: 'Please use the proper pattern'
        }
    }
});

Open in new window


Thanks in advance.
0
Comment
Question by:Eduardo Fuerte
  • 6
  • 4
10 Comments
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 41824707
You probably want to add a validation method for the regex like this
  // ADD A VALIDATOR METHOD FOR REGEX
  $.validator.addMethod('regex', function (value, element, regexp) { 
    var pattern = new RegExp(regexp);
    return pattern.test(value); 
  }, 'Please use the proper pattern');

  $("#myform").validate({
    //for debug only
    debug: true,
    rules: {
      field: {
        required: true,
        regex: /^(\d+|\d+,\d{1,2})$/
      }
    }
  });

Open in new window

0
 

Author Comment

by:Eduardo Fuerte
ID: 41826242
Hi

I don't know if I properly applied the code yoy suggested on existing field.

// Validation
         $('#entity-form').on('submit', function (e) {
        e.preventDefault();
    }).validate({

        ignore: ".ignore",
        errorClass: "state-error",
        validClass: "state-success",
        errorElement: "em",
        rules: {
            nome_reclamante: {
                required: true,
            },
            data: {
                required: true,
            },
            sise: {
                number: true,
            },
            
             //Field to be validated accordingly to your regex rule:
            custo: {
                number: true,
                //pattern: /^(\d+|\d+,\d{1,2})$/
                
                 rules: {
                    field: {
                    required: true,
                    regex: /^(\d+|\d+,\d{1,2})$/
                    }
                }
            }
               
            },
            reembolso: {
                number: true,
                //pattern: /^(\d+|\d+,\d{1,2})$/
                
            },
            //EF Set/2016 - FIM
   
            
        },
        messages: {
            nome_reclamante: {
                required: '',
            },
            sise: {
                number: '',
            },
            
            
            //EF Set/2016
            custo: {
                number: '',
            },
                    
            reembolso: {
                number: '',
            },
           ///EF Set/2016 - FIM
            
            
        },
        highlight: function (element, errorClass, validClass) {

            $(element).closest('.validar').addClass(errorClass).removeClass(validClass);
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).closest('.validar').removeClass(errorClass).addClass(validClass);
        },
        submitHandler: function (form) {
            
            var formData = new FormData(form);

            $.ajax({
                url: base_url('reclamacao/save'),
                type: 'post',
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json',
                data: formData,
                success: function (data) {

                    $("#procedencia").remove();
                    
                    if(data.hasOwnProperty('message')) {
                        
                        time_alert(data.message);
                        $('#entity-form').trigger('reset');
                    }
                    else if(data.hasOwnProperty('erro')) {
                        bootbox.alert(data.erro);
                    }

                    redrawDataTables();
                },
                error: function(jqXHR) {
                    bootbox.alert(jqXHR.responseText);
                }
            });
        }
    });
// End validate


 // ADD A VALIDATOR METHOD FOR REGEX
  $.validator.addMethod('regex', function (value, element, regexp) { 
    var pattern = new RegExp(regexp);
    return pattern.test(value); 
  }, 'Please use the proper pattern');

Open in new window


Could you give a look?
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 41826285
It looks correct - is it not working?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:Eduardo Fuerte
ID: 41826331
No, it isn't.
img002
First I had to correct my code (missing } ) to

      reembolso: {
                number: true,
                
                //EF Out/2016 - 01
               rules: {
                    field: {
                    required: true,
                    regex: /^(\d+|\d+,\d{1,2})$/
                    } 
                //---------------------------------
                }
            },
            //EF Set/2016 - FIM

Open in new window


It seens the 'regex'method is not fired...
0
 
LVL 60

Accepted Solution

by:
Julian Hansen earned 2000 total points
ID: 41826473
Here is a working sample
HTML
    <form id="myform">
      <input type="text" name="field" />
      <input type="submit" />
    </form>

Open in new window

jQuery
$(function() {
  // ADD A VALIDATOR METHOD FOR REGEX
  $.validator.addMethod('regex', function (value, element, regexp) { 
    var pattern = new RegExp(regexp);
    return pattern.test(value); 
  }, 'Please use the proper pattern');

  $("#myform").validate({
    //for debug only
    debug: true,
    rules: {
      field: {
        required: true,
        regex: /^(\d+|\d+,\d{1,2})$/
      }
    }
  });
});

Open in new window

0
 

Author Comment

by:Eduardo Fuerte
ID: 41826772
Hi

So I did:

Relevant parts of jQuery:

$(function () {
        $('#data, #recebido_em, #respondido_em, #data_atendimento, #enviado_dpto_em, #resposta_dpto_em').datetimepicker({
            format:'DD/MM/YYYY HH:mm:SS',
        });

        $('').datetimepicker({
            format:'DD/MM/YYYY',
        });
        
        //The code you gave:
        $.validator.addMethod('regex', function (value, element, regexp) { 
            var pattern = new RegExp(regexp);
            return pattern.test(value); 
        }, 'Please use the proper pattern');
    
   ....

 $('#entity-form').on('submit', function (e) {
        e.preventDefault();
    }).validate({

        ignore: ".ignore",
        errorClass: "state-error",
        validClass: "state-success",
        errorElement: "em",
        rules: {
            nome_reclamante: {
                required: true,
            },
            data: {
                required: true,
            },
            sise: {
                number: true,
            },
            
               //Validation you gave
            custo: {
                //number: true,
                debug: true,
                rules: {
                    field: {
                    required: true,
                    regex: /^(\d+|\d+,\d{1,2})$/
                 }
                }

Open in new window



The problem here is that the field is accepting alphanumeric characters:

img003
0
 

Author Comment

by:Eduardo Fuerte
ID: 41826965
@Julian

After some adjustments your code runs fine!

I adapted regex to
regex:/^[0-9]{1,2}([,.][0-9]{1,2})?$/

Open in new window


But the decimal places are supressed when the data is save to DB.
0
 

Author Closing Comment

by:Eduardo Fuerte
ID: 41827090
Your code runs perfectly.

The issue of decimal places is due MySQL doesn't accept decimal point is comma.
Solved with str_replace.

Thank you!
0
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 41827183
You are welcome.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to implement server side field validation and display customized error messages to the client.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

877 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question