Reputation:
I would like to validate and sanitize an input e.g "search" coming from a GET form request but i'm missing something about Javascript pattern matching.
This is the function where i'm currently working on:
function jsValidationAndSanitization() {
/**
Validate and sanitize every input that comes from an HTML form.
@return boolean
**/
var submittedInput = document.forms["form"]["search_input"].value;
if (submittedInput == "") {
alert("error: empty input");
return false;
}
if (submittedInput != "") {
// admitted chars ( white list )
var wl_pattern = /[A-z][0-9]/;
// loop for every chars in the submitted string
for (char in submittedInput) {
// if a bad char is present on the string return false
var result = char.match(wl_pattern); // INVERT THE MATCH OF RE HERE alert(result);
return false;
}
return true;
}
}
<form action="" method="GET" id="form" onsubmit="return jsValidationAndSanitization()">
<fieldset>
<legend>Test box</legend>
<label for="search" id="search_input">Search</label>
<input type="text" id="search_input" name="search_input" />
<input type="submit" id="submit" value="submit" />
</fieldset>
</form>
So i'm triyng to invert the matches ( only chars and numbers ) of of Javascript pattern matching but actually i didn't find a pretty way to do it and complete the function.
Any suggestions about it ?
Upvotes: 0
Views: 2297
Reputation: 565
You don't have to pattern match every character you could just match the string, and you could just return a match for any character outside of A-z or 0-9. The regexp match method returns an object if it finds a match and a null if nothing is found so in this to turn it to a boolean just prepend with an !, this will invert it, if you want to just turn it to a boolean then prepend with a !!.
function jsValidationAndSanitization() {
/**
Validate and sanitize every input that comes from an HTML form.
@return boolean
**/
var submittedInput = document.forms["form"]["search_input"].value;
if (submittedInput == "") {
console.log("error: empty input");
return false;
}
if (submittedInput != "") {
// non-admitted chars ( black list )
var wl_pattern = /[^A-z0-9]+/;
var result = submittedInput.match(wl_pattern);
if (result) { console.log(result); }
return !result;
}
return false; // Catch all to return false
}
Upvotes: 2