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
80 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 57

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 57

Expert Comment

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

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

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 57

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 57

Expert Comment

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

Featured Post

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

752 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