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
70 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 54

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 54

Expert Comment

by:Julian Hansen
ID: 41826285
It looks correct - is it not working?
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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 54

Accepted Solution

by:
Julian Hansen earned 500 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 Comment

by:Eduardo Fuerte
ID: 41826978
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 54

Expert Comment

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

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
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 invoke it on a web page. 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.: (CODE)

810 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