如何使用java和javascript进行特殊字符验证

时间:2015-02-11 16:40:08

标签: java javascript jquery validation jsp

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

这是.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中创建它。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

尝试

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>

答案 2 :(得分:0)

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

$('#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