views:

66

answers:

1

Hoo boy. A weird one I guess!

getting input from a form, I want to make sure there are no western characters, punctuation or numbers before sending it to a php script for creating some xml...

from form name = "a"

$('form').submit(function() {

text = ($(this).serialize());

text = text.substr(2,text.length)

text = text.replace(/[^\u3040-\u30FF^\uFF00-\uFFEF^\u4E00-\u9FAF^\u3400-\u4DBF]/g,'');

---> text goes to php script using .ajax

However, the Japanese is being converted to ASCII before it gets to the regex!

eg. あああ becomes %E3%81%82%E3%81%82%E3%81%82

Any suggestions?

A: 

I would swap it around and change the inputs before serializing, like this:

$('form').submit(function() {
  $(this).find(':text, textarea').val(function(i, v) {
    return v.replace(/[^\u3040-\u30FF^\uFF00-\uFFEF^\u4E00-\u9FAF^\u3400-\u4DBF]/g,'');
  });
  var text = ($(this).serialize());
  //submit form....
});

This uses .val() to get and replace the old value based on the regex before the serialization (and more importantly, encodeURIComponent() gets called in there).


Another alternative is to do the regex yourself in the middle of the .serialize() steps, like this:

$('form').submit(function() {
  var arr = $(this).serialzeArray();
  $.each(arr, function() {
    this.value = this.value.replace(/[^\u3040-\u30FF^\uFF00-\uFFEF^\u4E00-\u9FAF^\u3400-\u4DBF]/g,'');
  });
  var postData = $.param(arr);
});

.serialize() is really just $.param($(this).serializeArray()) so all we're doing is splitting it up here, taking the value of the {name:'name',value:'value'} object pairs in the array that .serializeArray() creates and running the regex on each. After that we're passing the changed array, western-character-less to $.param() to get serialized as a string.

Nick Craver
Will give it a whirl and let u know thanks!!
minikomi