We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to prevent user inputting special characters on the textbox?

how should i prevent the users to input special characters? ihave these codes :

  function registerDialog(){ 

  var message = '';

 if(loginBox != ''){ 
$.modal.close();
}

var html =  

         '<div>'
         +'<h4 style="background:#DADEE7;padding:10px;border:1px solid #ccc;"><i class="fa fa-chevron-circle-right "></i> Register</h4>'
         +'<input type="email" id="emailBox" placeholder="Email Address" style="width:90%; margin:10px auto 3px 10px;"/>'
         +'<input type="password" id="passwordBox" placeholder="Password" style="width:90%; margin:10px auto 3px 10px;"/>'
         +'<input type="text" id="realNameBox" style="width:90%;margin:10px auto 10px 10px;" placeholder="Complete Name."style="width:90%; margin:10px auto 3px 10px;" onkeypress="return restrictCharacters(this, event, alphaOnly);" />'
         +'<p id="infoBox" style="width:90%;margin-left:10px;margin-bottom:5px;"></p>'
         +'<p id="infoBox2" style="width:90%;margin-left:10px;margin-bottom:5px;"></p>'
         +'<p style="text-align:right;">'
         +'<button style="padding:5px;margin-right:5px;" id="signUpBtn">Submit</button>'
         +'<button style="padding:5px;margin-right:20px;" id="cancelBtn">Cancel</button>'
         +'</p>'
         +'</div>'

registerBox = $.modal(html, {
closeHTML:"",
containerCss:{
    backgroundColor:"#fff", 
    borderColor:"#fff", 
    minHeight: 250, 
    width: ($(window).width() > 320)? 320 : $(window).width() - 10,
    padding:0 
},
overlayClose:true,
opacity:80,
overlayCss: {
    backgroundColor:"#000"
},
    onShow : function (dialog) {

        $("#signUpBtn",dialog.data).click(function(){

                  var email = $('#emailBox').val();
                  var passwordBox = $('#passwordBox').val();
                  var realNameBox = $('#realNameBox').val();

                      if(email != '' && passwordBox != '' && realNameBox != '' && validateEmail(email) && filterName(realNameBox)){

                          $.ajax({
                              type  : 'get',
                              async : false,
                              url: baseUrl+'/Index/register',
                              data:{
                                    email   : email,
                                    password: passwordBox,
                                    realname: realNameBox
                              },
                              error: function(req,error){ 
                                console.log(req.statusText);
                              },
                              dataType: 'json',
                              cache: false,
                              success   : function(msg){  

                                if(msg.status == "OK"){ 
                                    message = 'Successfully Registered.';
                                    alert(message);
                                    window.location.reload();
                                }else{
                                    message = 'Registration failed, Email address already used.';
                                    $('#infoBox').html(message).css('color', 'red');
                                    return false;
                                } 
                            }

                           });
                      }else{  
                          if(email == ''){$('#emailBox').addClass('border-red');}else{$('#emailBox').removeClass('border-red');}
                          if(passwordBox == ''){$('#passwordBox').addClass('border-red');}else{$('#passwordBox').removeClass('border-red');}
                          if(realNameBox == ''){$('#realNameBox').addClass('border-red');}else{$('#realNameBox').removeClass('border-red');}
                          $('#infoBox').html('Please complete or correct the fields above marked in red.');

                          if(validateEmail(email) == false){
                              $('#emailBox').addClass('border-red'); 
                          }else{
                              $('#emailBox').removeClass('border-red'); 
                          }

                          return false;
                      }

        });

        $('#realNameBox').keypress(function(e){
             if (e.which == 13) {
                 $("#signUpBtn",dialog.data).click();

             }  
        });

        $("#cancelBtn",dialog.data).click(function(){

            var email = $('#emailBox').val('');
            var passwordBox = $('#passwordBox').val('');

            $.modal.close();
        });
    },
    onOpen: function (dialog) {
        dialog.overlay.fadeIn('fast', function () {
            dialog.data.hide();
            dialog.container.fadeIn('fast', function () {
                dialog.data.slideDown('fast');   
            });
        });
    },
    onClose: function (dialog) {
        dialog.data.fadeOut('fast', function () {
            dialog.overlay.slideUp('fast', function () {
                $.modal.close();
            });
        });

    }
   });
 }

i tried putting some code to restrict the text box from accepting the special characters but it seems like it's not working. thanks in advance! God Bless



37.0k
edited Jul '14

If you want to escape special characters you need to do that in he beginning of the controller before accessign database etc.

You can use build in php functions htmlspecialchars() or strip_tags() . Or you can use build-in-Phalcon functions like escapeHtml():

<?php
$e = new Phalcon\Escaper();
echo $e->escapeHtml($maliciousString);
?>

More here: https://docs.phalcon.io/en/latest/reference/escaper.html https://docs.phalcon.io/en/latest/api/Phalcon_Escaper.html

If you want to prevent pasting html characters using javascript that's a little bit more complicated, but it's probably possible. you need to check the input on every change and run it through some filtering javascript/jQuery code to strip the html tags and special characters like quotes semicolons etc.

edited Jul '14

i mean, rightbefore you enter it's already preventing you to input a special character. for example i pressed & but the textbox didn't displayed it cause it's already blocking it.



33.8k
Accepted
answer

With JS, you need to assign a function to keydown (or keyup) event, so when you press a special key character, JS will see if it is an special one. If it is, you need to rewrite the value of the text after you press the key (you know, text=text.substring(0, text.length - 1) I think). I don't know where to find a regexp that fits all special characters, but I think it will be more easy making a regexp that only matches letters and numbers (and characters like dots). I didn't tested it (I don't have experience with keydown but with keyup I did validation), but I think is the way to do it.