【问题标题】:How to make a special characters validation using java and javascript如何使用 java 和 javascript 进行特殊字符验证
【发布时间】:2015-02-11 16:40:07
【问题描述】:

我有一个网络应用程序。在客户表单中,我进行了空验证,但现在我必须测试该值是否具有特殊字符,例如:ÁÄÉëÍÏ......

这是 .java 空验证:

private void testFields(String name) {

    if (applicationField == null) {
        LOG.error("The request is invalid");
    }

    try {
        Field f = applicationField.class.getDeclaredField(name);
        f.setAccessible(true);

        Object value = f.get(applicationField);

        boolean emp = false;

        if (value instanceof String) {
            String strVal = (String) value;
            if (StringUtils.isEmpty(strVal)) {
                emp = true;
            }
        } else if (value == null) {
            emp = true;
        }

        if (emp) {
            addMissingField(name);
        }

    } catch (Exception e) {
        LOG.error("Failed to validate the field: " + name, e);
    }
}

private void addMissingField(String name){
    if (StringUtils.isEmpty(missingFields)) {
        missingFields = name;
    } else {
        missingFields += " " + name;
    }       
}

在 .jsp 中,我在提交按钮中执行此操作:

    $("#submit")
        .button()
        .click(function(event) {
            event.preventDefault();

            var submitButton = $(this); 

            submitButton.button("disable");

            $("input:text").each(function(idx,elem){
                $(elem).val($(elem).val().toUpperCase());       
            });

            var form = $("#customerForm");
            var action = form.attr('action');
            var queryString = form.serialize();

            console.log(notifier);

            var taskId = notifier.start("Processing Request");

            $.ajax({
                method: "post",
                url: action,
                data: queryString,
                statusCode: {
                    201: function() {
                        window.location.replace(".........");
                    }
                }
            }).always(function(data){

                notifier.done(taskId);
                submitButton.button("enable");

            }).done(function(data){

                if(data.missingFields){
                    messageDialog("Sorry, Missing required fields to register the application", true);
                    markMissingFields(data.missingFields);
                    console.log("This is the missing Fields: " + data.missingFields);
                } 

            }).fail(function(data){                                     
                messageDialog("There was an error processing the request", true);                   
            });

        });

因此,空验证完美运行。但有时用户插入数据如:MÖDRIC、JHÖN 或 CÁRLOS 会在数据库的差异化过程中产生问题。

我想知道如果值是空的或同时有特殊字符,我该怎么做才能包含特殊字符验证测试。

所以我需要一种在 .java 或 .jsp 中实现此功能的好方法。

【问题讨论】:

    标签: java javascript jquery validation jsp


    【解决方案1】:

    在 javascript 中你可以使用正则表达式:

    var str = "ábcde";
    var str2 = "abcd";
    var patt = new RegExp("[^a-zA-Z0-9\-\\/(),_\s]+") 
    var res = patt.test(str);
    patt.test(str); //true
    patt.test(str2); //false
    

    【讨论】:

      【解决方案2】:

      试试

      var charMap = {
                      "á": "a",
                      "à": "a",
                      "â": "a",
                      "á": "a",
                      "é": "e",
                      "è": "e",
                      "ê": "e",
                      "ë": "e",
                      "ï": "i",
                      "î": "i",
                      "ô": "o",
                      "ö": "o",
                      "û": "u",
                      "ù": "u"
                  };
      
      var str = "MÖDRIC";
      
      var normalize = function normalize(item) {
        var res = $.map(charMap, function(val, key) {
          return $.inArray(key.toUpperCase(), item.split("")) !== -1 
                 ? item.replace(key.toUpperCase(), val.toUpperCase()) : null
        })[0];  
        return res.length ? res : item
      };
      
      console.log(normalize(str),  normalize("JHÖN"), normalize("CÁRLOS"));
      

       // usage within `js` at OP
      
       $("input:text").each(function(idx, elem){
           $(elem).val(normalize(elem.value));       
       });
      

      jsfiddle http://jsfiddle.net/guest271314/m6d0du7z/

      另见How to make matcher ignore diacritics - JQUERY

          var charMap = {
                          "á": "a",
                          "à": "a",
                          "â": "a",
                          "á": "a",
                          "é": "e",
                          "è": "e",
                          "ê": "e",
                          "ë": "e",
                          "ï": "i",
                          "î": "i",
                          "ô": "o",
                          "ö": "o",
                          "û": "u",
                          "ù": "u"
                      };
      
          var str = "MÖDRIC";
          
          var normalize = function normalize(item) {
            var res = $.map(charMap, function(val, key) {
              return $.inArray(key.toUpperCase(), item.split("")) !== -1 
                     ? item.replace(key.toUpperCase(), val.toUpperCase()) : null
            })[0];  
            return res.length ? res : item
          };
          
          console.log(normalize(str),  normalize("JHÖN"), normalize("CÁRLOS"));
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

      【讨论】:

      • 我明白,但是,我在我的代码中找到了这样做的方法。
      • 还不行,在控制台:TypeError: normalize is not a function.
      • f可能,可以创建“stacksn-ps”blog.stackoverflow.com/2014/09/…,jsfiddlejsfiddle.net来演示吗? ?
      • 对不起,我不能使用它。但我只是在我的代码中包含:var charMap、var normalize 和更新帖子。我在控制台中收到了这条消息:TypeError: normalize is not a function。 $(elem).val(标准化(elem.value)); @guest271314
      【解决方案3】:

      我通过实现这段代码设法解决了这种情况:

      $('#inputid, #inputid').bind('keypress', function (event) {
          var regex = new RegExp(/^[a-zA-Z ]+$/); //Note i left a white space between brackets.
          var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
                  if (!regex.test(key)) {
                     event.preventDefault();
                     return true;
                  }
          });
      

      现在我阻止用户输入如下信息:

      CHARLÍE, PETE#R, MöDRIC 12.
      

      但他们可以输入如下名称:

      CHARLIE DA COSTE, JHON, PETER FARGO
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-16
        • 2023-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        相关资源
        最近更新 更多