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
84 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 58

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 58

Expert Comment

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

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

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 58

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 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 58

Expert Comment

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

Featured Post

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

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…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
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)
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

623 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