Hi,

Im looking for an easy method to validate the input of a form. Ideally I want to remove all spaces from the inputed text and also ensure that there are no speical characters within it other then a forward slash.

The input will look like this 192.168.1.1/24.

Thanks,

Dani AI

Generated

asked for removing spaces and blocking special characters except a forward slash (example: 192.168.1.1/24). is right to separate sanitisation from validation; pointed toward regexes; gave a quick idea. A robust, practical workflow is: 1) sanitise the raw input (strip whitespace and any characters that are not digits, dots or slash), 2) validate the cleaned string against an IPv4-with-optional-CIDR pattern, and 3) enforce the same checks server-side.

Example jQuery (sanitise then validate):

$('#myForm').on('submit', function(e){
  var $field = $('#ip');
  var s = $field.val().replace(/\s+/g, '').replace(/[^0-9.\/]/g, '');
  $field.val(s);

  var ipv4Cidr = /^(?:(?:25[0-5]|2[0-4]\d|1?\d{1,2})\.){3}(?:25[0-5]|2[0-4]\d|1?\d{1,2})(?:\/(?:[0-9]|[12]\d|3[0-2]))?$/;

  if (!ipv4Cidr.test(s)) {
    e.preventDefault();
    // mark field invalid, show message, etc.
  }
});

Notes and pitfalls:

  • The regex enforces each octet is 0–255 and an optional CIDR suffix of 0–32; it also rejects extra slashes or letters.
  • Use server-side parsing (language-specific IP/CIDR libraries or inet_pton equivalents) — never trust client-only checks.
  • If pasted text can contain non-breaking spaces or unusual Unicode, strip them (\s in JS covers common whitespace, but trim non-standard characters if needed).
  • If leading-zero octets should be disallowed (e.g., 192.168.001.001), adjust the octet pattern accordingly.

This gives a clean, user-friendly front-end fix while keeping validation strict and delegating final authority to the server.

Recommended Answers

All 3 Replies

Felix,

Strictly speaking, that's not validation (testing); it's sanitisation (modification).

Both validation and sanitisation can be performed with regular expressions as @stb says.

fast fix

[input].match(/[\d/]+/g).join('.');

might do the trick...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.