JS with no special characters and blank spaces

I am struggling to come up with JS that doesn’t allow special characters and no spacing on one particular field. I think this has something to do with Regex but I don’t fully understand. It’s not a required field so I don’t have to check for that. Just if used, no special characters and no blank spaces.

Any help would be appreciated.

Thank You.

Define ‘no special characters’. Do you want to include accented characters? Cyrilic? Kanji? Numbers? (Hint: It’s easier to specify what IS allowed, rather than what ISNT)

You have a good point.

I would want 0-9 and all letters, underscore, hyphen, and a period allowed, nothing else
Special characters like ! " # $ % & ’ ( ) *, etc not allowed.
And no blank spaces.

So again, ‘all letters’ is a little hazy, because in different languages, different letters exist.
For the moment, I will assume you mean the Latin alphabet a-z, A-Z. I will also assume that the item you’re checking is a single-line String.
You can extend this from there, if need be.

You’re correct that a regex is going to be the simplest method of checking. The HTML pattern attribute can take them, or we can handle it in Javascript if you want to do more complex things than simply preventing form submission.

Javascript’s Regex declaration specifies \w to be A-Z, a-z, 0-9, and the underscore (_). So we can use that. We want to add the hyphen, and period. Period is a gotcha character, because it has a special meaning. So we need to escape that character as \. Hyphen can cause issues too, because it can be used to represent a range of things (As in A-Z). So we’ll escape that one as well. \-
So we want there to be SOMETHING in the field. It needs to be a set of characters that match \w\.\-. More specifically, we’d like to know if there’s anything in the field that ISN’T those things. Regex defines a character set by putting square brackets around them. It defines “NOT this character set” by putting a carat (^) after the opening left-square-bracket. Our regex therefore is [^\w\.\-].
We wrap regexes in a pattern delimiter, /. /[^\w\.\-]/
The Javascript function String.match is used to check whether a string matches the regex supplied to it.

mystring.match(/[^\w\.\-]/)

If this function returns null, then the string complies with your rules. If it returns anything else, there was one or more illegal characters in it.

2 Likes

A regular expression will be the perfect answer for this.

The following HTML code is all that you need:

<form>
  <input type="text" name="username" required pattern="[0-9a-zA-Z_.-]*">
  <input type="submit">
</form>

When you attempt to submit that with invalid characters, the form shows an error message saying “Please use the requested format.”

We can improve on that error message too, making it more specific:

var input = document.querySelector("[name=username]");
input.oninvalid = function(event) {
    event.target.setCustomValidity("Special characters are not allowed.");
}

A simple demo is up at https://jsfiddle.net/pmw57/2zqcqpzx/

1 Like

Ooh. Paul teaching me things here too. the character class actually removes the need for the escaping of the period and hyphen.

For some reason the fiddle breaks when I put an invalid string in and then correct it, though…?

Paul,

I tried the code in your demo, works fine. So I am doing something wrong because I can’t get it working.

I substituted to my user name, added the required pattern. I tried the script in the header and also just above the and it doesn’t work.

Any suggestions?

Thank You

Oh yes, the custom validity should be set to empty when there’s no error.

input.oninput = function(event) {
    event.target.setCustomValidity("");
};

Here’s the update. https://jsfiddle.net/pmw57/2zqcqpzx/1/

2 Likes

With math problems, you’re asked to show your working.
Its the same sort of thing here too. Please show us what you’ve done.

1 Like

<input name="username"  value="<%=rs ("username")%>" maxlength="100" required pattern="[0-9a-zA-Z_.-]*">

<script type='text/javascript'>//<![CDATA[
    window.onload = function () {
        var input = document.querySelector("[name=username]");
        input.oninput = function (event) {
            event.target.setCustomValidity("");
        };
        input.oninvalid = function (event) {
            event.target.setCustomValidity("Special characters are not allowed.");
        };
    }//]]> 

</script>

That is not the only input that I have. I also have the following example with other alerts, etc:

function validate() {
var FirstName = document.getElementById("FirstName").value

if (FirstName == '') {
		alert('The first name field was left blank.')
		return false;
	}

Thanks. Is that ASP that you’re using on the back end?

Yes it is.

I also added type=text and that didn’t make any difference.

Is it outside of a form? A form with a submit button tends to be a good guarantee that things will work.

No. It’s within the form tag with other fields. The validation JS works fine. Would the onclick as below make a difference for this particular JS?

<input type="button" onclick="validate()" value="Submit">

Also, this is the form tag because it deals with an image upload, but again, doesn’t affect the other JS.

<form ENCTYPE="MULTIPART/FORM-DATA" method="post" action="post page">

That’s not something that can be determined until we take a look at it. Can you link us to a test page for the purpose of troubleshooting?

It’s a page that requires a login and it’s not a live site yet, so I can’t. I appreciate your offer of assistance though. Let me further look at it on my side my stripping out the rest of the code and first check the results. Will let you know my conclusions. Thank you.

Well based on that, i’m going to assume that by using a button rather than a submit type, it’s not firing the oninvalid event because the form is not being submitted regularly.

I assume your validate function is doing something like

<script>
function validate() {
  document.getElementById('form1').submit();
}
</script>

Which bypasses the invalid check.
Your validate() script should call something like

<script>
function validate() {
  if (document.getElementById('username').checkValidity()) {
	document.getElementById('form1').submit();
  }
}
</script>
2 Likes

This is the code for validate:

function validate() {

    var comments = document.getElementById("FirstName").value
    var comments = document.getElementById("LastName").value

if (FirstName == '') {
		alert('The first name field was left blank.')
		return false;
	}
	
if (LastName == '') {
		alert('The last name field was left blank.')
		return false;
	}

	document.mainform.submit()
}

with id = FirstName and LastName in the input tags

How is that validate function being triggered? If it’s via a click event, then that’s going to cause problems.
Making the button a type="submit" one lets you instead trigger the function on the submit event instead.

Not sure if I understand. Below is what I am using and the form submits just fine and validates the fields. Are you suggesting it would be best to make a change?