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
62 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 51

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 51

Expert Comment

by:Julian Hansen
ID: 41826285
It looks correct - is it not working?
0
 

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 51

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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

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 51

Expert Comment

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

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

705 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now